从组件类访问模板参考变量

问题描述 投票:90回答:1
<div>
   <input #ipt type="text"/>
</div>

是否可以从组件类访问模板访问变量?

即,我可以在这里访问它,

class XComponent{
   somefunction(){
       //Can I access #ipt here?
   }
}
angular typescript angular2-template
1个回答
137
投票

这是@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

© www.soinside.com 2019 - 2024. All rights reserved.