Issue
In the model
import { Type1, Type2 } from '.';
export type TypeComp = Type1 | Type2;
The selectedData$ observable is used in the some.component.ts and {{selectedData$ | async}} is used in its template.
What's the best way to check (or even to display) (ideally in the template, but per what I see there is no such way) if {{selectedData$ | async}} has Type1 or Type2.
UPD: To clarify, I'd like to use and display {{(selectedData$ | async).propAFromType1}} or another properties from Type1 or Type2, but without exceptions that will appear because these properties are the properties exactly of one Type Type1 or Type2, but not both (not TypeComp properties).
I don't want to put separate properties in both Type1 and Type2.
Solution
Since the value will be either in type1 or type2 please do a simple or check and render in the html like so.
Note: The
$anyis to get rid of the type check in HTML, since you are 100% certain that there will be only two properties, I am using this$anytype to override the typescript error!
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { Observable, of } from 'rxjs';
import 'zone.js';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
template: `
if you want the tag
<h1 *ngIf="$any(name$ | async) as test" [innerHTML]="test && (test.title || test.title2)">
</h1>
if you do not want the tag<br/><br/>
<h1 *ngIf="$any(name$ | async) as test" [outerHTML]="test && (test.title || test.title2)">
</h1>
`,
})
export class App {
name$: Observable<{ title: string } | { title2: string }> = of({
title: 'Angular',
});
}
bootstrapApplication(App);
References
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.