Access template reference variables from component class

<div>
<input #ipt type="text"/>
</div>

Is it possible to access the template access variable from the component class?

i.e., can I access it here,

class XComponent{
somefunction(){
//Can I access #ipt here?
}
}
129068 次浏览

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

@ViewChild('modal reference variable', { static: true }) name: ElementRef;

有时它不工作的模态。所以当我在角度上使用模态时,它会产生一个误差,所以我用这个。

@ViewChild('modal reference variable', { static: true }) name!: ElementRef;

如果你想不点击按钮就执行模式,它肯定会工作。