ViewChild
语法:@ViewChild(ChildDirective) child: ChildDirective;
其中参数:
- 类型:组件类名
- 字符串:包含模版本地变量的元素
demo —— 组件类名参数:
afterView.component.ts
export class AfterviewComponent implements OnInit {
constructor() { }
ngOnInit() {
}
greeting(name:string){
console.log('hello,'+name);
}
}
app.component.html
<app-afterview></app-afterview>
app.component.ts
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { StockInfo } from './child/child.component';
import { AfterviewComponent } from './afterview/afterview.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
@ViewChild(AfterviewComponent) greetdiv;
ngOnInit(){
this.greetdiv.greeting("Tom");
}
}
控制台输出:hello,Tom
demo ——本地变量参数:
app.component.html
<app-afterview #greet></app-afterview>
app.component.ts
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { StockInfo } from './child/child.component';
import { AfterviewComponent } from './afterview/afterview.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
@ViewChild('greet') greetdiv:AfterviewComponent ;
ngOnInit(){
this.greetdiv.greeting("Tom");
}
}
区别:
@ViewChild(AfterviewComponent)
可以获取组件为AfterviewComponent的参数
@ViewChild('greet')
可以获取本地变量#greet
ViewChildren: ViewChildren返回一个集合,可以用this.greetdivs['first'].greeting("Tom")
,ViewChild返回一个元素,匹配的第一个元素。
模版变量调用
app.component.html
<app-afterview #greet2></app-afterview>
<button (click)="greet2.greeting('Jerry')">按钮</button>