Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The `*ngFor` directive was used in the template, but neither the `NgFor` directive nor the `CommonModule` was imported

Tags:

angular

I'm new to angular and I can't use the ngFor component. This is the error:

The *ngFor directive was used in the template, but neither the NgFor directive nor the CommonModule was imported. Use Angular's built-in control flow @for or make sure that either the NgFor directive or the CommonModule is included in the @Component.imports array of this component.

And this is the code:

<h2>List</h2>

<ul>
    <li *ngFor="let c of contacts">
        {{c.id}} - {{c.name}}
    </li>
</ul>
like image 589
Raquel Oliveira Avatar asked Nov 19 '25 18:11

Raquel Oliveira


1 Answers

From Angular 17 with standalone components, things like ngFor need to be included in the imports array of your component.

e.g.

@Component({
  selector: 'app-contacts',
  standalone: true,
  imports: [NgFor],
  templateUrl: './contacts.component.html',
  styleUrl: './contacts.component.scss'
})

But better to use the new control flow syntax:

<ul>
  @for (c of contacts; track c.id) {
    <li>{{c.id}} - {{c.name}}</li>
  }
</ul>
like image 90
Emmanuel Avatar answered Nov 23 '25 14:11

Emmanuel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!