2016-09-22 17 views

Odpowiedz

72

To use-case dla @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...... 
    } 
} 

Oto demo pracy: 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 {} 
+0

Ale debugowanie Otrzymuję this.input się jako nieokreślony. – jackOfAll

+0

Tak jak wspomniałem, jest dostępna tylko PO zdarzeniu 'ngAfterViewInit()'. Musisz zaimportować 'ViewChild' z '@ angle/core' .. – mxii

+0

Ale jak możemy ustawić wartość? Próbowałem już 'this.ipt.nativeElement.setAttribute ('value', 'xxx');' ale nic się nie dzieje. I nie ma żadnych metod, takich jak 'value()' lub 'setValue()', nawet jeśli zadeklaruję to typu HTMLInputElement (opieram to na podpowiedziach/autouzupełnianiu IDE). W moim przypadku nie dbam o odczytanie wartości. Po prostu muszę ustawić różne wartości. – MrCroft

Powiązane problemy