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

I have this enum:

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

and my interface:

export SomeInterface {
    status?: Status;
}

and a simple use of includes method with in-line array creation in some.component.ts:

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

works as expected. However, within the 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). How do I overcome this?

Update:

I do have:

Status = Status;

in my some.component.ts, so that I can reference it from html.

Answer

I’ve created an 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)"

Leave a Reply

Your email address will not be published. Required fields are marked *