Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在Angular中将组件从父组件复制并传递到子组件?_Javascript_Angular - Fatal编程技术网

Javascript 如何在Angular中将组件从父组件复制并传递到子组件?

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>

如何从父组件复制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>

我可以通过将所需的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>