简体   繁体   中英

Angular8 / NG-ZORRO 8: Binding in ng-template of nzAction

Im using angular 8 with ng-zorro version 8.2.1.

I have a nz-card see https://ng.ant.design/components/card/en repeated by a *ngFor . For the actions, I need to access the property of *ngFor but it turns out that I can't access that from within the template.

<ng-template #boxActionDetails>
    <p>{{box.id}}</p>
</ng-template>
<nz-card *ngFor="let box of boxes" nzTitle="{{box.title}}" [nzActions]="[boxActionDetails]">
     <p>{{box.description}}</p>
</nz-card>

When executing the code above, I get the following js error

TypeError: Cannot read property 'id' of undefined

Unfortunately, I couldnt find any solution to solve the issue so I came up with the following workaround:

Store the data inside the html with [attr.boxid]="box._id"

<nz-card *ngFor="let box of boxes" nzTitle="{{box.title}}"
            [nzActions]="[boxActionLearn, boxActionEdit, boxActionDetails, boxActionDelete]" class="box" [attr.boxid]="box._id">
            <p>{{box.description}}</p>

Call a generic Function with event handler when clicking on the action with (click)="actionDetails($event)"

<ng-template #boxActionDetails>
        <i nz-icon nzType="unordered-list" (click)="actionDetails($event)"></i>
</ng-template>

Inside the action, iterate via the even target up to the parent which contains the data and use is for further processing.

actionDetails(event) {
    var target = event.target || event.srcElement || event.currentTarget;
    var boxid = target.parentNode.parentNode.parentNode.parentNode.parentNode.attributes.boxid.nodeValue;
}

You can declare the ng-template in the loop body, like this:

<nz-card *ngFor="let item of [true, true, true]; index as i"
         nzTitle="Card title" 
         [nzActions]="[action]">
  <p>Card content</p>
  <p>Card content</p>
  <p>Card content</p>
  <ng-template #action>
   <button nz-button>{{i}}</button>
  </ng-template>
</nz-card>

Live DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM