问题描述
在Angular 6应用中,我需要将一个组件作为其 ng-template .
In my Angular 6 app I need to pass a Component to another Component as its ng-template.
原因是我有一个 A组件,需要多次复制,但是每次必须包含不同的组件(我们称它们为 B组件, 组件C ),其具有相同的输入.
The reason is that I have a Component A that I need to replicate many times, but each time it has to include different components (let's call them Component B and Component C) which have the same Inputs.
组件A 模板:
<div class="row-detail-panel">
<h4 class="row-detail-panel-title">{{ newEntity ? 'Add new' : 'Edit this'}} {{ entityName }}</h4>
<!--THIS IS THE COMPONENT I WANT TO INJECT-->
<app-component-b
[inline]="true"
[form]="form"
></app-component-b>
<!--END-->
<!--some more html code here-->
</div>
然后我使用以下方法创建一个 Component A 实例:
And I create a Component A instance using:
<app-component-a
[entity]="row"
[entityName]="entityName"
></app-component-a>
因此,我考虑使用ng-template
,因此按如下所示更改 Component A 模板:
So I thought about using ng-template
, so changing the Component A template as follows:
<div class="row-detail-panel">
<h4 class="row-detail-panel-title">{{ newEntity ? 'Add new' : 'Edit this'}} {{ entityName }}</h4>
<ng-template></ng-template>
<!--some more html code here-->
</div>
并使用以下方法创建 Component A 实例:
And creating a Component A instance using:
<app-component-a
[entity]="row"
[entityName]="entityName"
>
<app-component-b
[inline]="true"
[form]="form" <!--PROBLEM: "form" does not exist here-->
></app-component-b>
</app-component-a>
因此,我可以轻松地将组件C 而不是组件B 注入为组件A 的ng-template:
So I can easily inject Component C instead of Component B as Component A's ng-template:
<app-component-a
[entity]="row"
[entityName]="entityName"
>
<app-component-c
[inline]="true"
[form]="form" <!--PROBLEM: "form" does not exist here-->
></app-component-c>
</app-component-a>
问题:
我需要注入到 Component B 或 Component C 的变量form
仅存在于 Component A 中,而 (位于组件A的父级中)(出于某些原因,我无法将其向上移动一级).
the variable form
that I need to inject to Component B or Component C exists only inside Component A and not in Component A's parent (for some reasons I cannot move it one level up).
我该如何解决这个问题?
How can I solve this problem?
推荐答案
您是否只是通过以下方式尝试过:
Have you tried by simply doing:
<app-component-a #compA
[entity]="row"
[entityName]="entityName">
<app-component-b
[inline]="true"
[form]="compA.form"
></app-component-b>
</app-component-a>
// component-a.html
<div class="row-detail-panel">
<h4 class="row-detail-panel-title">{{ newEntity ? 'Add new' : 'Edit this'}} {{ entityName }}</h4>
<ng-content></ng-content>
</div>
为使其正常工作,在A组件中定义的form
成员应该是公共的,最好是readonly
.
In order for this to work, the form
member defined in the A component should be public, and preferably readonly
.
这篇关于Angular将一个组件作为另一个组件的ng-template传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!