Pass component reference to component inside ngFor

2019-05-27 11:27发布

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条回答
倾城 Initia
2楼-- · 2019-05-27 12:12

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>
查看更多
登录 后发表回答