2016-09-22 30 views

Trả lời

72

Đó là một use-case cho @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...... 
    } 
} 

Dưới đây là một bản demo làm việc: 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

Nhưng trên gỡ lỗi Tôi nhận được this.input chính nó như là không xác định. – jackOfAll

+0

Như tôi đã đề cập, nó chỉ có sẵn sau khi sự kiện 'ngAfterViewInit()' được kích hoạt. Bạn phải nhập 'ViewChild' từ '@ angular/core' .. – mxii

+0

Nhưng làm cách nào chúng tôi có thể đặt giá trị? Tôi đã thử 'this.ipt.nativeElement.setAttribute ('value', 'xxx');' nhưng không có gì xảy ra. Và không có phương thức nào như 'value()' hay 'setValue()', ngay cả khi tôi khai báo nó kiểu HTMLInputElement (tôi đang dựa vào mã này trên mã gợi ý/tự động điền của IDE). Trong trường hợp của tôi, tôi không quan tâm đến việc đọc giá trị. Tôi chỉ cần đặt các giá trị khác nhau. – MrCroft

Các vấn đề liên quan