我创建了一个简单的UI,它包含两个组件(父和子) .
UI的作用是当我在Child组件的输入框中键入一些内容时 . 该值将使用ngModel更改 .
子组件以这种方式正常工作 .
// Child Component
@Component({
selector: 'child',
template: `
<p>{{sharedVar}}</p>
<input [(ngModel)]="sharedVar">
`
})
export class ChildComponent {
sharedVar: string;
}
现在我有一个父组件,我打算使用与Child Component相同的值 .
我将Child Component添加到Parent模板中,并使用依赖注入来调用Child Component的 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>
中的值不会更改 .
2 回答
您可以设置从子级到父级的事件 Launcher 通信(
outputs
) . 例如这样:和父母组件:
Demo: http://plnkr.co/edit/T2KH4nGKPSy6GEvbF1Nb?p=info
我们可以在父模板中使用
[(x)]
语法来实现与子进程的双向数据绑定 . 如果我们创建一个名为xChange
的Output属性,Angular将自动更新父属性 . 每当孩子改变值时,我们确实需要emit()
事件:Plunker
我在ParentComponent中使用
sharedVarParent
只是为了证明父和子中的名称不必相同 .