Angular 2:是否可以从组件类访问模板引用variables?
<div> <input #ipt type="text"/> </div>
是否有可能从组件类访问模板访问variables?
即,我可以在这里访问它,
class XComponent{ somefunction(){ //Can I access #ipt here? } }
这是@ViewChild
一个用例: https : @ViewChild
class XComponent{ @ViewChild('ipt') input: ElementRef; ngAfterViewInit(){ // this.input is NOW valid !! } somefunction(){ this.input.nativeElement...... } }
这是一个工作演示: https : //plnkr.co/edit/GKlymm5n6WaV1rARj4Xp?p=info
import {Component, NgModule, ViewChild, ElementRef} from '@angular/core' import {BrowserModule} from '@angular/platform-browser' @Component({ selector: 'my-app', template: ` <div> <h2>Hello {{name}}</h2> <input #ipt value="viewChild works!!" /> </div> `, }) export class App { @ViewChild('ipt') input: ElementRef; name:string; constructor() { this.name = 'Angular2' } ngAfterViewInit() { console.log(this.input.nativeElement.value); } } @NgModule({ imports: [ BrowserModule ], declarations: [ App ], bootstrap: [ App ] }) export class AppModule {}