Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
Angular: How to bind directives to elements with *ngFor

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>
...
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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>
about 4 years ago · Juan Pablo Isaza Report

0

<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>
about 4 years ago · Juan Pablo Isaza Report

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!