<div>
<input #ipt type="text"/>
</div>
是否可以从组件类访问模板访问变量?
即,我可以在这里访问它,
class XComponent{
somefunction(){
//Can I access #ipt here?
}
}
这是@ViewChild
的用例:
https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html
class XComponent {
@ViewChild('ipt', { static: true }) input: ElementRef;
ngAfterViewInit() {
// this.input is NOW valid !!
}
somefunction() {
this.input.nativeElement......
}
}
这是一个工作示例:
https://stackblitz.com/edit/angular-viewchilddemo?file=src%2Fapp%2Fapp.component.ts