Angular - 如何在 @if 模板流语法中使用值 0

问题描述 投票:0回答:3

我在 Angular 模板流语法中遇到 @if 问题。

RxJs Observable 中有一个值可用。因此,异步管道会有所帮助,并将值分配给变量。

@if (currentPageNumber$ | async; as currentPageNumber) {
// currentPageNumber is number

对于值 0,if 语句无效。所以我只排除空值...但现在 currentPageNumber 的值为布尔值。

@if ((currentPageNumber$ | async) !== null; as currentPageNumber) {
// currentPageNumber is boolean

如何检查 null 但保留变量与流的值?

javascript angular
3个回答
1
投票

您可以将值直接包装在模板中,这可能是了解

AsyncPipe
工作原理的最直接的方法。

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [AsyncPipe],
  template: `
    @if({value: (sub$ | async)}; as wrappedValue) {
      foo {{wrappedValue.value}}
    } @else {
      bar
    }
  `,
})
export class App {
  sub$ = new BehaviorSubject(0);
}

0
投票

如果您不喜欢在模板中嵌套 if-s,您可以使用以下方法(如 jeremy-denis 共享的方法)。

在这里,我正在修改响应,使其不再是“虚假”值,因此一旦

| async
被评估为“真实”值,您将获得下面渲染的块,并且您可以将
users
引用到访问号码。


@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule],
  template: `
      <pre>{{str$ | async | json}}</pre>
      @if (str$ | async; as users) {
           {{users | json}}   
      }
  `,
})
export class App {
  str$ = of(0).pipe(
    /// the delay will result in `null` value for the first 2sec
    delay(2000),
    map((x) => {
      // mutate the response to something that is not null and store the value
      return  {
        pageSize: 0
      };
    })
  );
}

0
投票

看起来像是

@if
语法的限制(
0
在 JS 中计算为 false,因此您不能使用该语法),您可以通过将值设置为字符串
'0'
来解决它,但您需要采取小心使用
+

将其转换回数字
import { AsyncPipe } from '@angular/common';
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { of } from 'rxjs';
import 'zone.js';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [AsyncPipe],
  template: `
    @if (check(currentPageNumber$ | async); as currentPageNumber) {
      {{+currentPageNumber}}
    }
  `,
})
export class App {
  name = 'Angular';
  currentPageNumber$ = of(0);

  check(value: any) {
    return value === 0 ? '0' : value;
  }
}

bootstrapApplication(App);

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.