首页 文章

子组件中的Angular 2 ngModel更新父组件属性

提问于
浏览
44

我创建了一个简单的UI,它包含两个组件(父和子) .

UI的作用是当我在Child组件的输入框中键入一些内容时 . 该值将使用ngModel更改 .

子组件以这种方式正常工作 .

// Child Component
@Component({
    selector: 'child',
    template: `
        <p>{{sharedVar}}</p>
        <input [(ngModel)]="sharedVar">
    `
})
export class ChildComponent {
    sharedVar: string;
}

现在我有一个父组件,我打算使用与Child Component相同的值 .

我将Child Component添加到Parent模板中,并使用依赖注入来调用Child Component的 sharedVar .

// Parent Component
@Component({
    selector: 'parent',
    template: `
        <h1>{{sharedVar}}</h1>
        <child></child>
    `,
    directives: [ChildComponent],
    providers: [ChildCompnent]
})
export class ParentComponent {
    sharedVar: string;
    constructor(child: ChildComponent) {
        this.sharedVar = child.sharedVar;
    }
}

问题是当我在输入框中输入时, <p> 中的值会自动更改,而父组件的 <h1> 中的值不会更改 .

2 回答

  • 90

    您可以设置从子级到父级的事件 Launcher 通信( outputs ) . 例如这样:

    @Component({
        selector: 'child',
        template: `
            <p>Child: {{sharedVar}}</p>
            <input [(ngModel)]="sharedVar" (ngModelChange)="change()">
        `
    })
    export class ChildComponent {
        @Output() onChange = new EventEmitter();
        sharedVar: string;
        change() {
            this.onChange.emit({value: this.sharedVar});
        }
    }
    

    和父母组件:

    @Component({
        selector: 'parent',
        template: `
            <h1>{{sharedVar}}</h1>
            <child (onChange)="sharedVar = $event.value"></child>
        `,
        directives: [ChildComponent]
    })
    export class ParentComponent {
        sharedVar: string;
        constructor() {
    
        }
    }
    

    Demo: http://plnkr.co/edit/T2KH4nGKPSy6GEvbF1Nb?p=info

  • 3

    我们可以在父模板中使用 [(x)] 语法来实现与子进程的双向数据绑定 . 如果我们创建一个名为 xChange 的Output属性,Angular将自动更新父属性 . 每当孩子改变值时,我们确实需要 emit() 事件:

    import {Component, EventEmitter, Input, Output} from 'angular2/core'
    
    @Component({
        selector: 'child',
        template: `
            <p>Child sharedVar: {{sharedVar}}</p>
            <input [ngModel]="sharedVar" (ngModelChange)="change($event)">
        `
    })
    export class ChildComponent {
        @Input() sharedVar: string;
        @Output() sharedVarChange = new EventEmitter();
        change(newValue) {
          console.log('newvalue', newValue)
          this.sharedVar = newValue;
          this.sharedVarChange.emit(newValue);
        }
    }
    
    @Component({
        selector: 'parent',
        template: `
            <div>Parent sharedVarParent: {{sharedVarParent}}</div>
            <child [(sharedVar)]="sharedVarParent"></child>
        `,
        directives: [ChildComponent]
    })
    export class ParentComponent {
        sharedVarParent ='hello';
        constructor() { console.clear(); }
    }
    

    Plunker

    我在ParentComponent中使用 sharedVarParent 只是为了证明父和子中的名称不必相同 .

相关问题