当值为 0 时,在 Computed() 或 Signals() 中使用 <number | null> 或 <number | undefined> 无法正常工作

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

我正在尝试在我的新 Angular 项目中使用信号并进行计算,但遇到了问题。

我有一个计算值,其中包含一个 id,它是一个数字。该 id 将由用户交互设置。在此之前它没有设置,所以我尝试将它设置为 null(或未定义)。

public selectedId = computed() {
  var result: number | null = null;
  // do some computations
  return result;
}

Now I wanted to use this in the template.

<div *ngIf="selectedId() as id">Current id: {{ id}}</div>

但这仅在 id 不为 0 时有效。一旦它为零,它的行为就好像它为空一样。我把一切都换成了数字 |未定义,但它导致了同样的问题。据我所知,只有 null >= 0 的特殊情况为 true。但也许有些事情发生了变化,或者信号和计算值的工作方式不同。

我知道我可以将其更改为 -1 代表“null”值,但我想知道是否有一些更好的解决方案来使用 number | null 或者如果这只是我们必须忍受的事情。

非常感谢。

angular typescript signals computed-properties
1个回答
0
投票

您需要更改语法,尝试将函数作为箭头函数发送到

computed
内,如下所示!还要确保您在
computed
内定义了一个信号,计算将自动检测更改并随着复杂的计算更新值!

import { NgIf } from '@angular/common';
import { Component, computed, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [FormsModule, NgIf],
  template: `
    <input type="text" [ngModel]="input()" (ngModelChange)="input.set($event)"/>
    <div *ngIf="selectedId() as id">Current id: {{id}}</div>
  `,
})
export class App {
  public input = signal<number | null>(null);

  public selectedId = computed(() => {
    var result: number | null = this.input();
    // do some computations
    return `result-${result}`;
  });
}

bootstrapApplication(App);

Stackblitz 演示

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