for example i have a ngfor
<ng-container *ngFor="let setting of settings | trackBy: trackById">
<button mat-button [matMenuTriggerFor]="menu">Menu</button>
<mat-menu #menu="matMenu">
<button mat-menu-item>{{ setting.value.caption }}</button>
</mat-menu>
</ng-container>
it will show a list of a button from how many value inside the ngfor settings.
and now i want to add some checkbox for example but only with button number 1.
it should be like this more less.
<button>
<button><checkbox>
<button>
any idea how to achieve like these?
sorry need to update my question. how about if i want to achieve like this
<button>
<button>
<checklist>
<button>
thanks
CodePudding user response:
Introduce 'first as' into your ngFor and add a container to check if it's the first element in iteration:
<ng-container *ngFor="let setting of settings; first as isFirst; trackBy: trackById">
(...code...)
<button...></button>
<ng-container *ngIf="isFirst">
<checkbox...></checkbox>
</ng-container>
</ng-container>
If by 'number 1' you indeed mean at position index==1, then use:
<ng-container *ngFor="let setting of settings; let i = index; trackBy: trackById">
(...code...)
<button...></button>
<ng-container *ngIf="i == 1">
<checkbox...></checkbox>
</ng-container>
</ng-container>
If you want to display checkbox for element at position 2 and button for every other:
<ng-container *ngIf="i == 2">
<checkbox...></checkbox>
</ng-container>
<ng-container *ngIf="i != 2">
<button...></button>
</ng-container>
or, shorter:
<ng-container *ngIf="i == 2; else showButton">
<checkbox...></checkbox>
</ng-container>
<ng-container #showButton">
<button...></button>
</ng-container>
CodePudding user response:
You can use the index to get the current index,
<ng-container *ngFor="let setting of settings | trackBy: trackById; let idx = index">
<button mat-button [matMenuTriggerFor]="menu">Menu</button>
<mat-menu #menu="matMenu">
<button mat-menu-item>{{ setting.value.caption }}</button>
<checkbox *ngIf="idx === 1" />
</mat-menu>
</ng-container>
