[英]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
I want to be able to accomplish an automatic update (2-way binding0 of a property that is in a parent controller from a child controller without the parent knowing that a @Output event needs to be passed into the child controller like I have in: 我希望能够完成自动更新(父控制器中的父控制器中的属性的2向binding0,而父控制器不知道需要将@Output事件传递到子控制器中,就像我在下面这样:
App 应用程式
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 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);
}
}
If by not doing any extra work , you mean that you want to remove the method valueChanged
from the parent. 如果不做任何额外的工作 ,则意味着您要从父级中删除方法
valueChanged
。 If so, you are on the right track by marking the two-way binding: 如果是这样,则通过标记双向绑定,您将走在正确的轨道上:
[(zModel)]='myValue'
the only thing you need to change in the child to achieve this two-way-binding is to actually add the suffix Change
to the exact name of your variable. 要实现双向绑定,您需要在子级中进行更改的唯一事情是实际上将后缀
Change
添加到变量的确切名称。 So instead of 所以代替
@Output()
zChange: EventEmitter<string> = new EventEmitter<string>();
it should be 它应该是
@Output()
zModelChange: EventEmitter<string> = new EventEmitter<string>();
as your @Input
is marked as zModel
. 因为您的
@Input
被标记为zModel
。
This also of course means that in the child valueChanged
you need to mark the correct variable name: 当然这也意味着在子
valueChanged
您需要标记正确的变量名称:
valueChanged(item){
this.zModelChange.emit(this.zModel);
}
So after these changes you can remove valueChanged
from parent, and the child tag would just look like this: 因此,在完成这些更改后,您可以从父项中删除
valueChanged
,而子项标签将如下所示:
<myinput [(zModel)]='myValue'></myinput>
Here's your updated Plunker: http://plnkr.co/edit/eYx5wXnYauzqKXtduOvX?p=preview 这是您更新的Plunker: http ://plnkr.co/edit/eYx5wXnYauzqKXtduOvX?p=preview
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.