我做了一个简单的UI,它包含两个组件(父和子).
UI的作用是当我在Child组件的输入框中键入一些内容时.该值将使用ngModel更改.
子组件以这种方式工作正常.
// Child Component
@Component({
selector: 'child',
template: `
<p>{{sharedVar}}</p>
<input [(ngModel)]="sharedVar">
`
})
export class ChildComponent {
sharedVar: string;
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个父组件,我打算使用与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;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是当我在输入框中输入时,值<p>会自动更改,而父组件中的值<h1>不会更改.