简体   繁体   English

Angular 6 *ngFor 指令不起作用

[英]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.将 cli 升级到 v6 后,我刚刚创建了一个新项目,并使用 Angular Material util 添加了仪表板布局。

I was just messing around and realized that ngFor was not working for me.我只是在胡闹,意识到 ngFor 不适合我。

I ensured that the CommonModule was being imported, I checked if other directives were working like *ngIf .我确保导入了 CommonModule,我检查了其他指令是否像*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.我只是将我的 app-test 组件放在由仪表板快速入门构建的卡片中,这是呈现的内容。

Screenshot:截屏: 在此处输入图片说明

Ng --Version:吴--版本: 在此处输入图片说明

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 . topics: ['C','C#']在这段代码中,typescript 如何处理它。 ['C','C#'] is a datatype of topics variable instead of assigning value for that variable. ['C','C#']topics变量的数据类型,而不是为该变量赋值。 so you should provide the data as like所以你应该像这样提供数据

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

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM