angular – @Input:双向数据绑定不起作用

前端之家收集整理的这篇文章主要介绍了angular – @Input:双向数据绑定不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图复制这个: 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>
对于使用[(xxx)](banana-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

也可以看看

> https://angular.io/docs/ts/latest/api/forms/index/NgModel-directive.html
> https://github.com/angular/angular/issues/11073#issuecomment-242563788

原文链接:https://www.f2er.com/angularjs/240438.html

猜你在找的Angularjs相关文章