Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
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>
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!