kittencup / angular2-ama-cn

angular2 随便问
691 stars 101 forks source link

在父组件里面方便的获取子组件的数据 #108

Open lovechuck opened 8 years ago

lovechuck commented 8 years ago

ng2 里面,子组件是一个输入表单,子表单输入框木有监听事件,采用双向绑定,木有按钮,如何在父组件里面方便的获取子组件的数据呢

kittencup commented 8 years ago
import {Component,EventEmitter,Output} from 'angular2/core';

@Component({
    selector: 'child-form',
    template: `
        <input [(ngModel)]="username" />
    `
})
class ChildForm {

    @Output() inputKeyUp:EventEmitter<string> = new EventEmitter();

    set username(value:string) {
        this.inputKeyUp.emit(value);
    }
}

@Component({
    selector: 'App',
    directives: [ChildForm],
    template: `
        <h1>ChildForm</h1>
        <child-form (inputKeyUp)="input($event)"></child-form>

        <p>
            {{username}}
        </p>
    `
})

export class App {

    username:string;

    input(username:string) {
        this.username = username;
    }
}