Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda