I have an <ng-container *ngFor='let column of columns'></ng-container>
which displays multiple times on the page because of the *ngFor
. I want to apply the "sticky" attribute (directive) to only the first of these ng-container elements. Not to the others. How can I do that? The output then should look like this:
<ng-container sticky></ng-container>
<ng-container></ng-container>
<ng-container></ng-container>
<ng-container></ng-container>
...
CodePudding user response:
The ngFor
directive has a first
variable that is true only for the first iteration.
ngIf
has an else
keyword that, in conjunction with a template variable can conditionally render one of two templates.
<ng-container *ngFor="let column of columns; first as isFirst">
<ng-container *ngIf="isFirst; else notFirst" sticky></ng-container>
<ng-template #notFirst></ng-template>
</ng-container>
CodePudding user response:
<ng-container>
will not exists in the DOM. It is used only to loop through the items and generate some content dynamically. So if you apply sticky
directive to it directly, it will not have any effect. But you can apply sticky
directive to elements that are generated by <ng-container>
. I suggest you do add one <div>
inside <ng-container>
as a wrapper to the content and apply sticky
directive to it. Also, you can use first
variable of *ngFor
to apply sticky
directive only to the first element.
<ng-container *ngFor='let column of columns; let first as first'>
<div *ngIf="first" sticky>
<!--Your actual content-->
<div>
<div *ngIf="!first">
<!--Your actual content-->
<div>
</ng-container>
CodePudding user response:
You can use index for this:
<ng-container *ngFor="let column of columns; let i = index">
<div *ngIf="i=0" sticky></div>
<div *ngIf="i!=0"></div>
</ng-container>