![](/img/trans.png)
[英]Angular Observable Get updated changed object from a parent to child component
[英]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向binding0,而父控制器不知道需要將@Output事件傳遞到子控制器中,就像我在下面這樣:
應用程式
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.