Angular 6 *ngFor 指令无效

Angular 6 *ngFor directive not working

我刚刚在将我的 cli 升级到 v6 后创建了一个新项目,并使用 Angular Material 实用程序添加了仪表板布局。

我只是在胡闹,发现 ngFor 对我不起作用。

我确保 CommonModule 被导入,我检查其他指令是否像 *ngIf 一样工作。是我做错了什么还是更新后有问题?

测试组件:

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>

我刚刚将我的应用程序测试组件放入了仪表板快速入门构建的卡片中,这是呈现的内容。

截图:

吴--版本:

您正在声明 topics 的类型,而不是初始化它

尝试

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() {}

}

您已声明变量但未对其进行初始化。试试这个

export class TestComponent implements OnInit {

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

      constructor() { }

      ngOnInit() {
      }

    }

解释:

topics: ['C','C#'] 在此代码中打字稿如何处理它。 ['C','C#']topics 变量的数据类型,而不是为该变量赋值。所以你应该提供像

这样的数据

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