'Angular - Create composed type of value, function or Observable and accessing it in Component template
I would like to create a type that can be a either value (string, bool, number, ...), function or observable and then be able to access it's value in the component template.
Motivation is to create flexible API for component input properties, where user can provide input as type that suits them the best (value, function or observable) and component should be "smart" enough to render the value according to it's type.
Having a common type for value and function would look like this:
// age.component.ts
type ValOrFunc<T> = T | ((...args: unknown[]) => T);
@Component({
selector: 'app-age',
...
})
class AgeComponent {
@Input()
age: ValOrFunc<number>
constructor() { }
getValue<T>(val: ValOrFunc<T>): T {
if (val instanceof Function) {
return val();
}
return val;
}
}
// age.component.html
<p>
Age is {{ getValue(age) }}
</p>
Now anyone using AgeComponent can provide age as either number or function and the value will be updated in the age component template.
Problem is when I want to add Observable into the equation.
// age.component.ts
type ValFuncOrObs<T> = T | ((...args: unknown[]) => T) | Observable<T>;
@Component({
selector: 'app-age',
...
})
class AgeComponent {
@Input()
age: ValFuncOrObs<number>
constructor() { }
getValue<T>(val: ValFuncOrObs<T>): T {
???
}
}
Now how should the getValue implementation look like?
I was thinking also about checking the type in the template and using AsyncPipe when the value is observable, but that feels tedious and would add a lot of repeating code for component with many input properties.
// age.component.html
<p>
Age is {{ isObservable(age) ? age | async : getValue(age) }}
</p>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
