我有shared-components
模块。它由app.module
导出,然后导入到我想要使用它的模块中。在shared-components
模块中,我有一个组件,它应该基于3个*ngIf
元素进行渲染(取决于数量<、>或=到0(。该组件通过@Import someNumber(初始化为未定义(接收一个数字
组件标签包含在*ngFor
循环中。
检查HTML代码,我可以看到组件接收到someNumber的正确值。并对插值值{{someNumber && (someNumber < 0)}
进行了正确的评价。但是没有*ngIf
被渲染。
(我将用似乎相关的(匿名(代码逐步升级这个问题。(
child.component.html
{{(someNumber !== undefined) && (someNumber > 0)}} <!-- Renders true or false as expected -->
{{(someNumber !== undefined) && (someNumber === 0)}} <!-- Renders true or false as expected -->
{{(someNumber !== undefined) && (someNumber < 0)}} <!-- Renders true or false as expected -->
<ng-container *ngIf="(someNumber !== undefined) && (someNumber > 0)">...</ng-container> <!-- Never renders! -->
<ng-container *ngIf="(someNumber !== undefined) && (someNumber === 0)">...</ng-container> <!-- Never renders! -->
<ng-container *ngIf="(someNumber !== undefined) && (someNumber < 0)">...</ng-container> <!-- Never renders! -->
子组件.ts
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'child-component',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input() someNumber : number | undefined;
constructor() { }
ngOnInit(): void {
}
}
parent.component.html
<div id="stuff" class="container">
<div *ngIf="y.length === 0" class="loading">Data is <b>loading</b>...</div>
<div *ngFor="let x of y;" class="card">
<div class="card-body">
<h5 class="card-title">{{ x.b | uppercase }}</h5>
<div class="row">
<ng-container *ngIf="x.a">
<div class="col-10">
<ul>
(...)
</ul>
</div>
<div class="childComponent Container col-1">
<child-component [someNumber]="x.a.someNumber"></child-component>
</div>
</ng-container>
<ng-container *ngIf="!x.a">
(...)
</ng-container>
</div>
</div>
</div>
<a routerLink="/" class="btn btn-primary w-25">< Back</a>
</div>
通用模块
如果您不将CommonModule
添加到拥有组件的模块中:
插值将起作用:
{{3 + 3}} <!-- 6 -->
但是,任何包含*ngFor
的内容都不会呈现。
<ng-container *ngFor="true">U will not see me</ng-container> <!-- Never renders! -->
<ng-container *ngFor="false">U will not see me</ng-container> <!-- Never renders! -->
<ng-container *ngFor="...">U will not see me</ng-container> <!-- Never renders! -->