Bailey Miller
Bailey Miller

Reputation: 1513

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

Upvotes: 1

Views: 8509

Answers (2)

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38663

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#']

Upvotes: 4

manish kumar
manish kumar

Reputation: 4692

you are declaring the type of topics instead of initializing it

try

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: string[]

  constructor() { 
      this.topics=['C','C#'];
  }

  ngOnInit() {}

}

Upvotes: 0

Related Questions