Pass component reference to component inside ngFor (Angular)

大憨熊 提交于 2020-01-14 02:23:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!