在 Angular 中使用 ngForOf 时,在模板中使用联合类型和类型保护

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

如果我在

array: (A | B)[]
中使用
*ngFor
似乎选项是在整个模板上使用
$any()

有没有办法正确地做到这一点?

我完全避免使用

$any()
打字,但感觉很糟糕。我在模板中看到的有关类型联合的所有其他帖子都是特定的实现,总体感觉很hacky。

angular angular-directive
2个回答
0
投票

编写一个定义类型的方法,该方法将在 ngFor 中使用!

get arrayA(): A {
    return this.array as A;
}

get arrayB(): B {
    return this.array as B;
}

0
投票

我想你可以定义

export type typeAB=A & B
arrayAB=this.array as typeAB

并循环数组AB

<div *ngFor="let element of arrayAB">{{element}}</div> 

例如使用按钮

  toogleChange()
  {
    if (this.arrayAB==this.array2 as typeAB[])
       this.arrayAB=this.array as typeAB[]
    else
       this.arrayAB=this.array2 as typeAB[]
  }
© www.soinside.com 2019 - 2024. All rights reserved.