我制作了一个简单的UI,它由两个组件(父组件和子组件)组成.
UI的作用是,当我在子组件的输入框中键入一些内容时.该值将使用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>
中的值不会更改.