Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

148
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda