Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use union types in the HTML template side of an Angular component

In the HTML part of an Angular component, I want to display a checkbox or an icon on different conditions. With a permissive model { checked?: boolean; icon?: string }, I can do it like that:

<input type="checkbox" [(ngModel)]="item.checked" *ngIf="!item.icon">
<i class="{{item.icon}}" *ngIf="item.icon">

This model enables invalid states like having both checked and icon. Having a stronger model could rely on an union type: { checked: boolean } | { icon: string }. But it does not work anymore in the HTML, because checked nor icon are available at the "union type" level but only on the left or right case.

Is there a way to use this model in some tweaked HTML template?

like image 320
Romain Deneau Avatar asked May 04 '20 19:05

Romain Deneau


People also ask

Can I use HTML template in Angular?

An Angular HTML template renders a view, or user interface, in the browser, just like regular HTML, but with a lot more functionality. When you generate an Angular application with the Angular CLI, the app. component. html file is the default template containing placeholder HTML.

How do you use a union in TypeScript?

In TypeScript, a union type variable is a variable which can store multiple type of values (i.e. number, string etc). A union type allows us to define a variable with multiple types. The union type variables are defined using the pipe ( '|' ) symbol between the types. The union types help in some special situations.

Can I check a type against a union type in TypeScript?

We can differentiate between types in a union with a type guard. A type guard is a conditional check that allows us to differentiate between types. And in this case, a type guard lets us figure out exactly which type we have within the union.


1 Answers

It's a bit late, but I have a similar problem right now. If found a solution, but it's not very elegant. I hope there is something better... You can wrap your item in $any() operator like so:

<input type="checkbox" [(ngModel)]="$any(item).checked" *ngIf="!item.icon">
<i class="{{$any(item).icon}}" *ngIf="item.icon">

That should work.

like image 105
wrzr123 Avatar answered Oct 20 '22 00:10

wrzr123