2016-09-22 27 views

cevap

72

: 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

Ama tarih: https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html

İşte
class XComponent{ @ViewChild('ipt') input: ElementRef; ngAfterViewInit(){ // this.input is NOW valid !! } somefunction(){ this.input.nativeElement...... } } 

çalışan bir demo Ben hata ayıklama Ben bu tanımsız olarak. – jackOfAll

+0

Daha önce de belirttiğim gibi, sadece mevcut olan 'ngAfterViewInit()' adlı etkinlik başlatıldı. ViewChild'i '@ açısal/çekirdekten' almanız gerekiyor .. – mxii

+0

Ama bir değeri nasıl ayarlayabiliriz? Bu.ipt.nativeElement.setAttribute ('value', 'xxx'); 'denedim; ancak hiçbir şey olmuyor. Ve HTMLInputElement türünü bildirsem bile (IDE'nin kod ipucu/otomatik tamamlamasında bunu yapıyorum), 'value()' veya 'setValue()' gibi bir yöntem yoktur. Benim durumumda, değeri okumayı umursamıyorum. Sadece farklı değerler belirlemem gerek. – MrCroft

İlgili konular