子组件中的Angular 2 ngModel更新父组件属性
我制作了一个简单的UI,由两个部分(父级和子级)组成。
I made a simple UI which consist two components (parent and child).
UI的作用是,当我在子组件。该值将使用ngModel更改。
What the UI does is that when I type some stuff in the input box of the Child component. The value will change using ngModel.
子组件可以正常工作。
// Child Component
@Component({
selector: 'child',
template: `
<p>{{sharedVar}}</p>
<input [(ngModel)]="sharedVar">
`
})
export class ChildComponent {
sharedVar: string;
}
现在我有一个父组件,我打算使用与Child相同的值
Now I have a parent component which I intend to use the same value as Child Component.
我将子组件添加到父模板中,并使用依赖项注入来调用子组件的 sharedVar
。
I added the Child Component into the Parent template, and use dependency injection to call Child Component's sharedVar
.
// Parent Component
@Component({
selector: 'parent',
template: `
<h1>{{sharedVar}}</h1>
<child></child>
`,
directives: [ChildComponent],
providers: [ChildCompnent]
})
export class ParentComponent {
sharedVar: string;
constructor(child: ChildComponent) {
this.sharedVar = child.sharedVar;
}
}
问题是我在输入中键入框,< p>
中的值会自动更改,而父组件的< h1>
中的值不会更改。
The problem is as I'm typing in the input box, the value in <p>
changes automatically while the value in parent component's <h1>
do not change.
我们可以在 [(x)]
语法中使用父模板与子模板实现双向数据绑定。如果我们创建名为 xChange
的Output属性,Angular将自动更新父属性。每当孩子更改值时,我们确实需要 emit()
一个事件。
We can use the [(x)]
syntax in the parent template to achieve two-way databinding with the child. If we create an Output property with the name xChange
, Angular will automatically update the parent property. We do need to emit()
an event whenever the child changes the value however:
import {Component, EventEmitter, Input, Output} from 'angular2/core'
@Component({
selector: 'child',
template: `
<p>Child sharedVar: {{sharedVar}}</p>
<input [ngModel]="sharedVar" (ngModelChange)="change($event)">
`
})
export class ChildComponent {
@Input() sharedVar: string;
@Output() sharedVarChange = new EventEmitter();
change(newValue) {
console.log('newvalue', newValue)
this.sharedVar = newValue;
this.sharedVarChange.emit(newValue);
}
}
@Component({
selector: 'parent',
template: `
<div>Parent sharedVarParent: {{sharedVarParent}}</div>
<child [(sharedVar)]="sharedVarParent"></child>
`,
directives: [ChildComponent]
})
export class ParentComponent {
sharedVarParent ='hello';
constructor() { console.clear(); }
}
我使用了 sharedVarParent
在ParentComponent中只是为了证明父母和孩子的名字不必相同。
I used sharedVarParent
in the ParentComponent just to demonstrate that the names don't have to be the same in the parent and child.