angulartypescriptngforangular17

Angular - Get error NG0303 when using *ngFor


I want to use the for loop in Angular. This is my code for app.component.ts.

enter image description here

export class AppComponent {
  title = 'CatsBookProject';

  postText = [
    'Hello , i am here to meet new friends and make a friends relationship',
    'Hello everyone, Iam glad you are here',
    'Hey, my name is Susanne. I amm 2 years old',
    'I like eating cookies.'
  ]
  postImgs = [
    'assets/Imge/img1.png',
    'assets/Imge/im21.png',
    'assets/Imge/img3.jpg',
    'assets/Imge/img4.jpg',
  ]

  buttonClicked() {
    alert("What's up");
  }
}

And this is the app.component.html:

enter image description here

 <app-stroy *ngFor='let i of [0, 1, 2, 3]' [img]='postImgs[0]' [text]='postText[0]'></app-stroy> 

and I have this error:

enter image description here

NG0303: Can't bind to 'ngForOf' since it isn't a known property of 'app-stroy' (used in the '_AppComponent' component template).

  1. If 'app-stroy' is an Angular component and it has the 'ngForOf' input, then verify that it is included in the '@Component.imports' of this component.
  2. If 'app-stroy' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@Component.schemas' of this component to suppress this message.
  3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@Component.schemas' of this component.

This is the code for story.component.ts:

import { Component, Input, OnInit } from '@angular/core';
@Component({
  selector: 'app-stroy',
  standalone: true,
  imports: [],
  templateUrl: './stroy.component.html',
  styleUrl: './stroy.component.scss'
})
export class StroyComponent implements OnInit {
  @Input() text: string = '';
  @Input() img: string = '';

  constructor() { }

  ngOnInit(): void {
  }
}

I need some help.


Solution

  • You should include NgForOf or CommonModule in the imports array of the AppComponent.

    import { NgForOf } from '@angular/common';
    // Or
    //import { CommonModule } from '@angular/common';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [RouterOutlet, HeaderComponent, StroyComponent, NgForOf, CommonModule],
      templateUrl: './app.component.html',
      styleUrl: './app.component.scss',
    })
    export class AppComponent {
    
    }
    

    Demo @ StackBlitz