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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With