Home > Net >  Why ngfor directive is not working, though I have created proper object in Typescript class
Why ngfor directive is not working, though I have created proper object in Typescript class

Time:12-19

I have created proper Ingredient object in Typesript, also proper "model" for the object. Though ngfor directive is not working. I am getting this error "NG0303: Can't bind to 'ngforOf' since it isn't a known property of 'a'" on inspecting in browser.

My model code

export class Ingredient {
constructor(public name: string, public amount: number){}

}

My TypeScript code

import { Component, OnInit } from '@angular/core';
import { Ingredient } from '../shared/ingredient.model';

@Component({
  selector: 'app-shopping-list',
  templateUrl: './shopping-list.component.html',
  styleUrls: ['./shopping-list.component.css']
})
export class ShoppingListComponent implements OnInit {

  ingredients: Ingredient[] = [

    new Ingredient ("Apple", 5),
    new Ingredient ("Tomato", 5)
  ];

  constructor() { }

  ngOnInit(): void {
  }

}

My HTML code

<div >
    <div >
        <app-shopping-edit></app-shopping-edit>
        <hr>
        <ul class = "list-group">
            <a class = "list-group-item" 
            style = "cursor : pointer"
            *ngfor = "let ingredient of ingredients">
            {{ ingredient.name }}({{ ingredient.amount}})
            </a> 
        </ul>
    </div>
</div>

Page is loading properly, but ingredients are not loading. On inspecting in browser this error "NG0303: Can't bind to 'ngforOf' since it isn't a known property of 'a'" is coming.

Can someone please help.

CodePudding user response:

Try moving the *ngFor inside the ul tag.

Edit: You have a typo.. It's *ngFor="", not *ngfor="".

CodePudding user response:

If you are inside AppModule check if you have BroswerModule in the imports array there. If you are in some different module then check if CommonModule is a part of that module's array. CommonModule provides us with core Angular features like *ngIf or *ngFor in your specific case. Also watch out, you typed *ngfor instead *ngFor.

  • Related