1

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>
...
NeNaD
  • 18,172
  • 8
  • 47
  • 89
  • Maybe [this](https://stackoverflow.com/questions/44597077/apply-a-directive-conditionally) can be helpful but I don't know if it is really a duplicate or not because of the `*ngFor` that might make it a bit more difficult – Arnaud Denoyelle Nov 02 '21 at 14:49

3 Answers3

4

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>
D M
  • 5,769
  • 4
  • 12
  • 27
  • 1
    please note @nenad-milosavljevic answer to this question about having the `sticky` directive on `` – Mazdak Nov 02 '21 at 16:07
  • It's possible that sticky is a [structural directive](https://angular.io/guide/structural-directives) and the provided code is simply missing the [appropriate shorthand](https://angular.io/guide/structural-directives#shorthand-examples); though that would require an additional element as well, since multiple structural directives on the same element are not supported. You both are right that the attribute cannot be directly applied as-is. – D M Nov 02 '21 at 20:34
1

<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>
NeNaD
  • 18,172
  • 8
  • 47
  • 89
1

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>
Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85