Angular 4:如何在父组件不做任何额外工作的情况下让父组件的值被子组件中的更改值更新

Angular 4: How can I get the Parent Component's value to be updated by a changed value in a child Component without the Parent doing any extra work

我希望能够完成自动更新(父控制器中的 属性 的 2 向绑定 0 来自子控制器,而父控制器不知道需要传递 @Output 事件像我一样进入子控制器:

Plunker

应用程序

import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'


@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>

    <div class="app">
      Parent: {{ myValue }}
      <myinput 
         [(zModel)]='myValue'
         (zChange)='valueChanged($event)'
      ></myinput> 
    </div>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
  myValue: string = 'Hello World';
  valueChanged(event) {
    //alert('app: onchange (' + event + ")");
    this.myValue = event;
  }
}

MyinputComponent

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

@Component({
    selector: 'myinput',
    template: `
      <hr>
   <div >
        Inside Component: <u>{{ zModel }}</u> <br/><br/>
        <input type="text" 
            [(ngModel)]="zModel"
            (input)="valueChanged($event)"
            >
   </div>
  `
})
export class MyinputComponent {
    @Input() 
    zModel: string = '';

    @Output()
    zChange: EventEmitter<string> = new EventEmitter<string>();

  valueChanged(item){
    //alert('onchange (' + this.zModel + ')');
        this.zChange.emit(this.zModel);
    }
}

如果不做任何额外的工作,你的意思是你想从父级中删除方法valueChanged。如果是这样,那么通过标记双向绑定就走在了正确的轨道上:

[(zModel)]='myValue'

要实现这种双向绑定,您唯一需要在子项中进行更改的是实际将后缀 Change 添加到变量的确切名称。所以而不是

@Output()
zChange: EventEmitter<string> = new EventEmitter<string>();

应该是

@Output()
zModelChange: EventEmitter<string> = new EventEmitter<string>();

因为您的 @Input 被标记为 zModel

这当然也意味着在子valueChanged中你需要标记正确的变量名:

valueChanged(item){
  this.zModelChange.emit(this.zModel);
}

因此,在这些更改之后,您可以从父标签中删除 valueChanged,子标签将如下所示:

<myinput [(zModel)]='myValue'></myinput> 

这是您更新的 Plunker:http://plnkr.co/edit/eYx5wXnYauzqKXtduOvX?p=preview