Angular2 : two way binding inside parent/child component

后端 未结 5 1036
天涯浪人
天涯浪人 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:20

    You need to use input / output elements in the child component, as described below:

    @Component({
      selector:'input-test'
      template: `
        
    {{name}}
    ` }) export class InputTestComponent { @Input() name:string; @Output() nameChange:EventEmitter = new EventEmitter(); }

    When a change is detected, you need to fire an event using the EventEmitter:

    onSubmit() {
      this.nameChange.emit(this.name);
    }
    

    This way the bound element of the parent component will be automatically updated when using the following syntax:

    
    

    You can notice that you can leverage, the ngModelChange event if you want to detect input change instead of using form submission:

    @Component({
      selector:'input-test'
      template: `
        
    {{name}}
    ` }) export class InputTestComponent { @Input() name:string; @Output() nameChange:EventEmitter = new EventEmitter(); onChange(newName) { this.name = newName; this.nameChange.emit(this.name); } }

提交回复
热议问题