为什么Angular内置指令不能在单个组件上工作



我正在使用

  • 角度^9.1.11
  • 节点12.18.0

我的问题:

ngIfngFor这样的内置指令不起作用,我知道我必须导入CommonModule

我的场景:我有一个模块,有一个路由器组件和三个子组件。所有组件都导入到模块中。除一个组件(也没有错误(外,所有组件都按预期工作(*ngIf*ngFor…(。

我的组件:

import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss'],
})
export class MyComponent implements OnInit {
list = [1,2,4]
constructor() {}
ngOnInit(): void {}
}

我的模板:

<div class="container">
{{list.length}} // 3
<div *ngFor="let item of list">TEST</div> // not looping
<div *ngIf="true">TEST</div> // not showing
</div>

我可以创建一个工作正常的新组件,并将我的更改cherrypick到新组件中,但我想知道这是如何发生的。该组件以前确实工作过,我担心即使我创建了一个新组件,它将来也可能再次损坏。

这有点晚了。但我自己设法解决了这个问题。

问题是,该组件不是导入CommonModule的模块的一部分,而CommonModule是某些功能所需的,有些功能可能会被认为是给定的。

希望这能帮助到任何遇到同样问题的人。

Angular在同一元素上不支持多个结构指令。作为一种变通方法,使用
<ng-container *ngIf="show">
<div *ngFor="let thing of stuff">
{{log(thing)}}
<span>{{thing.name}}</span>
</div>
</ng-container>

最新更新