Search code examples
angularangular-directive

Angular 6 *ngFor directive not working


I just created a new project after upgrading my cli to v6 and added the dashboard layout using the Angular Material util.

I was just messing around and realized that ngFor was not working for me.

I ensured that the CommonModule was being imported, I checked if other directives were working like *ngIf. Am I doing something wrong or is something broken after updating?

Test Component:

import { Component, OnInit } from '@angular/core';

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

  topics: ['C','C#']

  constructor() { }

  ngOnInit() {
  }

}

Html:

<div>
  <p>Topics</p>
  <ul>
    <li *ngFor="let topic of topics">{{topic}}</li>
  </ul>
</div>

I just placed my app-test component inside the cards built by the Dashboard quickstart, here is what renders.

Screenshot: enter image description here

Ng --Version: enter image description here


Solution

  • You are declared the variable but you are not initialize it. just try this

    export class TestComponent implements OnInit {
    
        topics: [] = ['C','C#']
    
          constructor() { }
    
          ngOnInit() {
          }
    
        }
    

    Explanation:

    topics: ['C','C#'] in this code how typescript handle it like . ['C','C#'] is a datatype of topics variable instead of assigning value for that variable. so you should provide the data as like

    topics :[]= ['C','C#']