如何从父级复制2个组件并传递给子级组件?
<!-- this is only shown on desktop -->
<div>
<my-custom-component [myInput]="myInput1"></my-custom-component>
<my-custom-component [myInput]="myInput2"></my-custom-component>
</div>
<!-- this is only shown on mobile -->
<my-other-component>
<!-- how can i pass all my-custom-component in to this component? -->
<!-- this works but I'd like to use an elementRef or something similar -->
<my-custom-component [myInput]="myInput1"></my-custom-component>
<my-custom-component [myInput]="myInput2"></my-custom-component>
</my-other-component>
答案 0 :(得分:0)
我能够通过将所需的html包装在模板中来实现此目的。然后,我可以将其注入到需要的页面上的任何位置:
在html中:
<ng-template #exampleTemplate>
<my-custom-component [myInput]="myInput1"></my-custom-component>
<my-custom-component [myInput]="myInput2"></my-custom-component>
<ng-template>
<my-other-component>
<ng-container #exampleContainer></ng-container>
</my-other-component>
在组件中:
@ViewChild('exampleContainer', { static: true, read: ViewContainerRef })
exampleContainer: ViewContainerRef;
@ViewChild('exampleTemplate', { static: true })
exampleTemplate: TemplateRef<any>;
ngAfterContentInit(): void {
this.exampleContainer.createEmbeddedView(this.exampleTemplate);
}
然后在my-other-component的html中:
<ng-content></ng-content>