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

时间:2016-09-22 06:18:13

标签: angular typescript angular2-template

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

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

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

class XComponent{
   somefunction(){
       //Can I access #ipt here?
   }
}

1 个答案:

答案 0 :(得分:124)

这是@ViewChildhttps://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html

的用例
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 {}