Angular 6中*ngFor指令失效问题求助
解决Angular v6中*ngFor指令不生效的问题
你遇到的*ngFor不生效的情况,和Angular升级到v6、Angular Material的仪表盘布局都没关系,问题出在你组件里topics数组的定义语法上!
看你提供的组件代码:
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() { } }
你写的topics: ['C','C#']是类型标注,不是给变量赋值。这就导致topics实际上是undefined,ngFor没办法遍历一个未定义的值——而ngIf能正常工作是因为它可以处理undefined这类falsy值,但*ngFor必须要有一个可迭代的对象(比如数组)才行。
修正后的组件代码
把数组定义改成赋值语句就可以了:
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[] = ['C','C#']; constructor() { } ngOnInit() { } }
修正之后,*ngFor就能正常遍历数组,渲染出你想要的列表项了。
补充验证
你当前的渲染效果(如图所示)里只有“Topics”文字,没有列表项,正好对应topics未定义的情况:
你的Angular版本信息:
内容的提问来源于stack exchange,提问作者Bailey Miller
相关产品推荐
相关产品推荐

