DynamicContentLoader文档没有解释我如何正确加载子组件的输入.假设我有一个孩子喜欢:
@Component({
selector: 'child-component',
template: '<input type="text" [(ngModel)]="thing.Name" />'
})
class ChildComponent {
@Input() thing : any;
}
Run Code Online (Sandbox Code Playgroud)
和父母一样:
@Component({
selector: 'my-app',
template: 'Parent (<div #child></div>)'
})
class MyApp {
thing : any;
constructor(dcl: DynamicComponentLoader, elementRef: ElementRef) {
dcl.loadIntoLocation(ChildComponent, elementRef, 'child');
}
}
Run Code Online (Sandbox Code Playgroud)
我应该如何thing进入子组件,以便两个组件可以绑定同一个数据.
我试着这样做:
@Component({
selector: 'my-app',
template: 'Parent (<div #child></div>)'
})
class MyApp {
thing : any;
constructor(dcl: DynamicComponentLoader, elementRef: ElementRef) {
dcl.loadIntoLocation(ChildComponent, elementRef, 'child').then(ref => {
ref.instance.thing = this.thing;
});
}
}
Run Code Online (Sandbox Code Playgroud)
它有点工作,但它们没有像你期望的那样同步.
基本上我试图通过在角度1中使用ng-include来实现同样的事情,其中子项是动态确定的组件并与其父项共享模型.
提前致谢 ...
我为你的问题做了一些测试,我无法重现它.
这是我的子组件的内容:
@Component({
selector: 'child-component',
template: `
<div>
Child component - <input type="text" [(ngModel)]="thing.name" />
</div>
`
})
export class ChildComponent {
@Input() thing : any;
constructor() {
}
}
Run Code Online (Sandbox Code Playgroud)
以下是父组件的内容:
@Component({
selector: 'my-dyn-parent',
template: `
<div>
Parent component - <input type="text" [(ngModel)]="thing.name" /> (<br/>
<div #child></div>
<br/>)
</div>
`
})
export class ParentComponent {
thing : any;
constructor(dcl: DynamicComponentLoader, elementRef: ElementRef) {
this.thing = { name: 'test name' };
dcl.loadIntoLocation(ChildComponent, elementRef, 'child')
.then((compRef:ComponentRef) => {
compRef.instance.thing = this.thing;
});
}
}
Run Code Online (Sandbox Code Playgroud)
所以我在同一个元素上绑定了两个输入:一个在父组件中,一个在子组件中.当我更新一个输入中的值时,另一个值将在另一个输入中更新.
因此,两个组件共享同一个实例并可以更新它.也许我在你的用例中遗漏了一些东西,所以请随时告诉我!
希望它对你有帮助,蒂埃里
| 归档时间: |
|
| 查看次数: |
4218 次 |
| 最近记录: |