Angular 2: Можно ли получить доступ к ссылочным переменным шаблона из класса компонентов? <div> <input #ipt type="text"/> </div> Можно ли получить доступ к переменной доступа к шаблону из класса компонента? i.e., могу ли я получить к нему доступ сюда, class XComponent{ somefunction(){ //Can I access #ipt here? } } Ответ 1 Это пример использования для @ViewChild: https://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 {}
Ответ 1 Это пример использования для @ViewChild: https://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 {}