NgIf 和零:为什么模板没有被渲染?
NgIf and zero: Why is the template not being rendered?
我有以下 observable on 和 Angular 组件:
count$: Observable<number>;
this.count$ = this.getCount();
通过使用以下我得到值 0(零);
this.count$.subscribe(x => console.log(x));
在我的模板上:
<a routerLink="/dash" *ngIf="(count$ | async)">
<ng-container *ngIf="count$ | async as count">
Count: {{count}}
</ng-container>
</a>
如果 count$
为 1,我得到 Count: 1
,但如果 count$
为 0,则内容 Count: 0
甚至不会呈现。
知道为什么吗?
您正在使用 ngIf,这意味着您正在有条件地显示您的值。当值为 0 时,您的条件评估为 false,因此不会显示。
如 this issue, this is the expected behavior. NgIf
coerces the given expression into a boolean
value. If the expression evaluates into a falsy 值(转换为 false 的值)中所讨论的那样,将不会呈现内容。
以下是 javascript 当前转换为 false 的所有值:
if (false)
if (null)
if (undefined)
if (0)
if (NaN)
if ('')
if ("")
if (``)
万一有人在寻找解决方法,这太愚蠢了,但它确实有效:
<ng-container *ngIf="{ len: count$ | async } as ctx">
<ng-container *ngIf="ctx.len !== null"
{{ ctx.len }}
</ng-container>
</ng-container>
解释:
- 在名为
ctx
的对象内部将 count
捕获为 len
- 因为
*ngIf
现在正在查看一个对象,而不是值,它将评估为 truthy 并呈现 ng-container
- 现在我们用
ctx.len !== null
检查我们是否得到了实际值
- 我们可以使用
ctx.len
访问该值
在这些情况下:
if (false)
if (null)
if (undefined)
if (0)
if (NaN)
if ('')
if ("")
if (``)
上面说的都是假的,我的建议是:
通过使用 pipe(map()) 将其转换为字符串,这样 '0' 就不是假的,它仍然可以与数字管道等一起使用
希望这对其他人有所帮助。
我有以下 observable on 和 Angular 组件:
count$: Observable<number>;
this.count$ = this.getCount();
通过使用以下我得到值 0(零);
this.count$.subscribe(x => console.log(x));
在我的模板上:
<a routerLink="/dash" *ngIf="(count$ | async)">
<ng-container *ngIf="count$ | async as count">
Count: {{count}}
</ng-container>
</a>
如果 count$
为 1,我得到 Count: 1
,但如果 count$
为 0,则内容 Count: 0
甚至不会呈现。
知道为什么吗?
您正在使用 ngIf,这意味着您正在有条件地显示您的值。当值为 0 时,您的条件评估为 false,因此不会显示。
如 this issue, this is the expected behavior. NgIf
coerces the given expression into a boolean
value. If the expression evaluates into a falsy 值(转换为 false 的值)中所讨论的那样,将不会呈现内容。
以下是 javascript 当前转换为 false 的所有值:
if (false)
if (null)
if (undefined)
if (0)
if (NaN)
if ('')
if ("")
if (``)
万一有人在寻找解决方法,这太愚蠢了,但它确实有效:
<ng-container *ngIf="{ len: count$ | async } as ctx">
<ng-container *ngIf="ctx.len !== null"
{{ ctx.len }}
</ng-container>
</ng-container>
解释:
- 在名为
ctx
的对象内部将 - 因为
*ngIf
现在正在查看一个对象,而不是值,它将评估为 truthy 并呈现ng-container
- 现在我们用
ctx.len !== null
检查我们是否得到了实际值
- 我们可以使用
ctx.len
访问该值
count
捕获为 len
在这些情况下:
if (false)
if (null)
if (undefined)
if (0)
if (NaN)
if ('')
if ("")
if (``)
上面说的都是假的,我的建议是: 通过使用 pipe(map()) 将其转换为字符串,这样 '0' 就不是假的,它仍然可以与数字管道等一起使用
希望这对其他人有所帮助。