【发布时间】:2016-05-21 13:20:46
【问题描述】:
我制作了一个简单的 UI,它包含两个组件(父组件和子组件)。
UI 的作用是当我在 Child 组件的输入框中键入一些内容时。该值将使用 ngModel 更改。
这样子组件可以正常工作。
// Child Component
@Component({
selector: 'child',
template: `
<p>{{sharedVar}}</p>
<input [(ngModel)]="sharedVar">
`
})
export class ChildComponent {
sharedVar: string;
}
现在我有一个父组件,我打算使用与子组件相同的值。
我将子组件添加到父模板中,并使用依赖注入调用子组件的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> 中的值不会更改。
【问题讨论】:
-
不要注入组件,你使用
@Inputangular.io/docs/ts/latest/api/core/Input-var.html将值传递给子组件,模板创建的实例和你通过指定提供者创建的实例是两个不同的实例。跨度>
标签: typescript angular angular2-ngmodel