Javascript 如何在Angular中将组件从父组件复制并传递到子组件?
如何从父组件复制2个组件并传递给子组件Javascript 如何在Angular中将组件从父组件复制并传递到子组件?,javascript,angular,Javascript,Angular,如何从父组件复制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 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>
我可以通过将所需的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);
}
<ng-content></ng-content>
@ViewChild('exampleContainer',{static:true,read:ViewContainerRef})
示例容器:ViewContainerRef;
@ViewChild('exampleTemplate',{static:true})
示例模板:TemplateRef;
ngAfterContentInit():void{
this.exampleContainer.createEmbeddedView(this.exampleTemplate);
}
然后在我的另一个组件的html中:
@ViewChild('exampleContainer', { static: true, read: ViewContainerRef })
exampleContainer: ViewContainerRef;
@ViewChild('exampleTemplate', { static: true })
exampleTemplate: TemplateRef<any>;
ngAfterContentInit(): void {
this.exampleContainer.createEmbeddedView(this.exampleTemplate);
}
<ng-content></ng-content>