【问题标题】:Angular 6 *ngFor directive not workingAngular 6 *ngFor 指令不起作用
【发布时间】:2018-11-09 00:27:35
【问题描述】:

在将 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>

我刚刚将我的 app-test 组件放在由仪表板快速入门构建的卡片中,这是呈现的内容。

截图:

Ng --版本:

【问题讨论】:

  • 你有那个 li 的 css 吗?还是没有css?
  • 没有 css 它创建了 css 文件,但我没有对其应用任何东西
  • 你的控制台有输出吗?就像我的意思是一个错误..
  • 不,这是令人困惑的部分,chrome 调试器中没有错误。
  • topics: ['C','C#'] -> : 应该是 =

标签: angular angular-directive


【解决方案1】:

你被声明了变量,但你没有初始化它。试试这个

export class TestComponent implements OnInit {

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

      constructor() { }

      ngOnInit() {
      }

    }

解释:

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

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

【讨论】:

  • 嗯,现在是凌晨 4 点 36 分,我意识到这是多么愚蠢的错误,因为我睡着了。感谢收看这个。
  • 没错。请注意,您应该使用= 分配值,而不是:
  • @deezg 是的,我看到我显然只是半睡半醒,感谢您发现这一点。
  • @deezg 已更新。
【解决方案2】:

您是在声明 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: string[]

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

  ngOnInit() {}

}

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 2019-01-06
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 2018-12-21
    • 2018-12-17
    • 1970-01-01
    • 2018-04-12
    相关资源
    最近更新 更多