将组件引用传递给ngFor(Angular)内部的组件 [英] Pass component reference to component inside ngFor (Angular)
问题描述
如果两个组件都在ngFor中,如何将组件引用传递给另一个组件?
How can I pass component reference to another component if both components are in ngFor?
<div *ngFor="let address of fields?.addresses">
<div>
<o-lookup-dropdownlist></o-lookup-dropdownlist>
<o-lookup-dropdownlist [cascade]="!!!linkToUpper o-lookup-dropdownlist !!!!"></o-lookup-dropdownlist>
</div>
</div>
类似的东西:
<div *ngFor="let address of fields?.addresses; let i = index">
<div>
<o-lookup-dropdownlist #first{{i}}></o-lookup-dropdownlist>
<o-lookup-dropdownlist [cascade]="'first' + i"></o-lookup-dropdownlist>
</div>
</div>
用例:(@methgaard)
我需要组件引用,因为第二个下拉列表取决于第一个下拉列表的结果(例如,国家->邮政编码).如果我有组件引用,则可以禁用第二个o-lookup-dropdownlist
,直到第一个o-lookup-dropdownlist
具有值. (在选择国家之前,没有必要选择邮政编码).
Use case: (@methgaard)
I need component reference because second dropdownlist depends on result of the first one (country -> post code for example). If I have a component reference, I can disable second o-lookup-dropdownlist
until first one has a value. (There is no point in selecting post code before you select country).
推荐答案
*ngFor="let address of fields?.addresses; let i = index"
的扩展版本如下:
<ng-template ngFor [ngForOf]="fields?.addresses" let-address="$implicit" let-i="index">
<div>...</div>
</ng-template>
对于ng-template
,角度创建具有自己范围的EmbeddedView
.
For ng-template
angular creates EmbeddedView
that has its own scope.
因此,您可以在*ngFor
中使用相同的模板引用变量:
So you can just use the same template reference variable inside *ngFor
:
<o-lookup-dropdownlist #first></o-lookup-dropdownlist>
<o-lookup-dropdownlist [cascade]="first"></o-lookup-dropdownlist>
这篇关于将组件引用传递给ngFor(Angular)内部的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!