@Input:双向数据绑定无法正常工作

时间:2016-11-22 16:42:21

标签: angular data-binding

我正在尝试复制这个:http://plnkr.co/edit/OB2YTMJyeY3h9FOaztak?p=preview (这个plunker是有效的示例,我希望得到相同的结果,但是我的代码却没有工作)

=============================================== ===================

我有这个简单的双向绑定,我正在尝试更新像父子一样的字符串属性

问题:点击" 从父级更新"时,两个绑定都会更新。但是当点击" 从孩子更新"时,只有孩子会更新!

这看起来很简单,我可以做错什么?

注意:我使用了角度CLI来运行项目

=============================================== ===================

父组件:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-my-dad',
  templateUrl: './my-dad.component.html',
  styleUrls: ['./my-dad.component.css']
})
export class MyDadComponent {

  parentModel: string;

  constructor() {}

  updateModel(){
    this.parentModel += ' parent';
  }
}

父模板

<h2>Parent: {{ parentModel }} </h2> 
<button (click)="updateModel()"> update from parent </button>

<app-my-child [(model)]="parentModel"></app-my-child>

子组件

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-my-child',
  templateUrl: './my-child.component.html',
  styleUrls: ['./my-child.component.css']
})
export class MyChildComponent {

  @Input() model: string;

  constructor() { }

  updateModel(){
    this.model += ' child';
  }
}

儿童模板:

<h2>Child: {{ model }} </h2>
<button (click)="updateModel()"> update from child </button>

2 个答案:

答案 0 :(得分:13)

对于使用[(xxx)](ban-in-a-box)语法的双向绑定,您需要@Input()@Output()匹配的名称,如

@Input() myProp:String;
@Output() myPropChange:EventEmitter<String> = new EventEmitter<String>;

另见https://angular.io/docs/dart/latest/guide/template-syntax.html#!#two-way

对于使ngModel生效的双向绑定,您的组件需要实现ControlValueAccessor

另见

答案 1 :(得分:0)

对上面的@Gunter进行详细阐述:

  1. 子组件必须具有匹配的EventEmitter属性类型,该属性类型具有相同的通用数据类型并用@Output()装饰
  2. 必须调用上述属性的emit方法。通常使用更改子属性值的方法进行此调用。

因此,您的代码必须具有:

  1. @Output() modelChange: EventEmitter<String> = new EventEmitter<String>(); 在子组件中。
  2. 子组件的this.modelChange.emit(model);方法中的{li> updateModel()(调用emit方法)。
相关问题