问题
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>
Something like that:
<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>
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).
回答1:
Expanded version of *ngFor="let address of fields?.addresses; let i = index"
will look like:
<ng-template ngFor [ngForOf]="fields?.addresses" let-address="$implicit" let-i="index">
<div>...</div>
</ng-template>
For ng-template
angular creates EmbeddedView
that has its own scope.
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>
来源:https://stackoverflow.com/questions/46443711/pass-component-reference-to-component-inside-ngfor-angular