angular - 从组件类访问模板引用变量

标签 angular typescript angular2-template

<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

关于angular - 从组件类访问模板引用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39631594/

相关文章:

javascript - 为什么 Angular 不允许我将参数传递给提供者的 useFactory 中的函数?

javascript - 如何将 Angularfire2 添加到我的 Angular 项目中?

javascript - 如何继续检查数组直到满足特定条件

Angular 2 - 将条件样式应用于指令的子 HTML 元素

angular - Bootstrap Grid System 在 mat-expansion-panel 中不起作用

css - 在组件范围之外更新样式 - Angular 2

angular - 使用 *ngFor 访问对象的键和值

node.js - 30 天后自动删除 MongoDB 文档

Angular 2 : data binding with routing children

data-binding - 在html模板angular 2中动态设置组件属性