Angular 2 ngModel in child component updates parent component property

前端 未结 2 1046
傲寒
傲寒 2020-12-02 07:46

I made a simple UI which consist two components (parent and child).

What the UI does is that when I type some stuff in the input box of the Child component. The valu

2条回答
  •  [愿得一人]
    2020-12-02 08:22

    We can use the [(x)] syntax in the parent template to achieve two-way databinding with the child. If we create an Output property with the name xChange, Angular will automatically update the parent property. We do need to emit() an event whenever the child changes the value however:

    import {Component, EventEmitter, Input, Output} from 'angular2/core'
    
    @Component({
        selector: 'child',
        template: `
            

    Child sharedVar: {{sharedVar}}

    ` }) 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: `
    Parent sharedVarParent: {{sharedVarParent}}
    `, directives: [ChildComponent] }) export class ParentComponent { sharedVarParent ='hello'; constructor() { console.clear(); } }

    Plunker

    I used sharedVarParent in the ParentComponent just to demonstrate that the names don't have to be the same in the parent and child.

提交回复
热议问题