Angular2 : two way binding inside parent/child component

后端 未结 5 1052
天涯浪人
天涯浪人 2020-12-09 08:24

Version: \"angular2\": \"2.0.0-beta.6\"

I would like to implement a two way binding inside a parent/child component case.

On my child component, I\'m using t

5条回答
  •  渐次进展
    2020-12-09 09:10

    You can setup two-way data binding between parent and child component in the following ways:

    
    
    
    

    According to Angular - Template Syntax - Two-way binding:

    Angular offers a special two-way data binding syntax for this purpose, [(x)]. The [(x)] syntax combines the brackets of property binding, [x], with the parentheses of event binding, (x).

    
    

    The [(x)] syntax is easy to demonstrate when the element has a settable property called x and a corresponding event named xChange.

    @Input() counter: number;
    @Output() counterChange = new EventEmitter();
    

    The two-way binding syntax is really just syntactic sugar for a property binding and an event binding. Angular desugars the ChildComponent binding into this:

    
    

    Example: https://stackblitz.com/edit/angular-two-way-data-binding-between-parent-and-child-component?file=src%2Fapp%2Fapp.component.ts

    import { Component, Input, Output, EventEmitter } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      template: `
      
    {{counter}}
    ` }) export class AppComponent { counter = 0; increment() { this.counter++; } onCounterChange(counter: number) { this.counter = counter; } } @Component({ selector: 'app-child', template: `
    {{counter}}
    `, }) export class ChildComponent { @Input() counter: number; @Output() counterChange = new EventEmitter(); constructor() { } increment() { this.counterChange.emit(++this.counter); } }

提交回复
热议问题