2016-11-22 79 views
4

我试图复制这个: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'; 
    } 
} 

子模板:

回答

4

对于使用[(xxx)](香蕉在一箱)语法双向绑定,您需要和@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

又见

+0

这工作!但为什么我不能复制我发布的那个重要人物呢? (http://plnkr.co/edit/OB2YTMJyeY3h9FOaztak?p=preview) 也许它被弃用? 谢谢! – eneoes

+0

Plunker今天无法正常工作: -/ –

+0

现在可以运行Plunker,但无法重现。无论按什么按钮,这两个字符串都会更新。 –