简体   繁体   English

包括检查 Angular 组件中的内联数组创建。html 不编译

[英]Includes check with inline array creation in Angular component.html does not compile

I have this enum :我有这个enum

export enum Status {
    SOME_VAL = "SOME_VAL",
    SOME_VAL_2 = "SOME_VAL_2",
    SOME_VAL_3 = "SOME_VAL_3";
}

and my interface :和我的interface

export SomeInterface {
    status?: Status;
}

and a simple use of includes method with in-line array creation in some.component.ts :以及在some.component.ts中简单地使用includes内联数组创建的方法:

let someVal: boolean = [Status.SOME_VAL, Status.SOME_VAL_2].includes(this.someObject.status);

works as expected.按预期工作。 However, within the some.component.html :但是,在some.component.html

<div *ngIf="[Status.SOME_VAL, Status.SOME_VAL_2].includes(someObject.status)">
    ...
</div>

gives this warning:给出这个警告:

Argument type Status is not assignable to parameter type Status.SOME_VAL | Status.SOME_VAL_2

and doesn't compile.并且不编译。 Converting to:转换为:

<div *ngIf="$any([Status.SOME_VAL, Status.SOME_VAL_2]).includes(someObject.status)">
    ...
</div>

gets rid of the warning, since I believe erases the method's signature, and does make the code compile, but does not work as expected, always evaluates to false without error or warning (possibly resulting in an error of which the logs I cannot see).摆脱警告,因为我相信会删除方法的签名,并且确实使代码编译,但不能按预期工作,总是在没有错误或警告的情况下评估为false (可能导致我看不到日志的错误) . How do I overcome this?我该如何克服呢?

Update:更新:

I do have:我有:

Status = Status;

in my some.component.ts , so that I can reference it from html .在我的some.component.ts中,以便我可以从html引用它。

I've created an AsPipe :我创建了一个AsPipe

@Pipe({
  name: 'as'
})
export class AsPipe implements PipeTransform {

  transform<T>(value: any, args: T): T {
    return value as T;
  }
}

and use it as follows in the template:并在模板中按如下方式使用:

*ngIf="([Status.SOME_VAL, Status.SOME_VAL_2] | as: [Status]).includes(someObject.status)"

You need the enum instance to do that.你需要枚举实例来做到这一点。 To do that, declare a variable in.ts that holds enum reference and can be used in the.html template.为此,请声明一个变量 in.ts 来保存枚举引用并且可以在 .html 模板中使用。 For example:例如:

In ts:在 ts 中:

public status = Status;

In html:在 html 中:

<div *ngIf="[status.SOME_VAL, status.SOME_VAL_2].includes(someObject.status)">
    ...
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM