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

201
Visualizações
Best practice for initializing a variable when using @Input decorator in Angular

Let's assume we have an Interface Customer:

export interface Customer {
    name: string;
    age: number;
    phone: string;
}

Now we have a parent component and we want to pass an instance of Customer to the child component:

<child-component [customer]="instanceOfCustomer"></child-component>

After that we need to use @Input decorator to get the data in the child component. (We assume passing the instance is mandatory to use this component and this component will not work without passing the instance)

@Input() customer:Customer;

The problem is that we need to initialize customer somewhere and I think there are 3 approaches to avoid the error in Typescript:

  1. Initializing an empty customer in the constructor:

    this.customer = {
        name: "";
        age: 0;
        phone: "";
    }
    
  2. Change strictPropertyInitialization to false

  3. Just adding the ! prefix (Which I think I should use because no one should use this child component without passing the relative customer)

    @Input() customer!:Customer;
    

I want to know what approach should I use to avoid property initialization error in case of using @Input decorator.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

you should use setter https://angular.io/guide/component-interaction#intercept-input-property-changes-with-a-setter

or you can also use your 3rd approach.

there is already some answers for this too.

refer below answers for more details :

Make directive @Input required

about 4 years ago · Juan Pablo Isaza Relatório

0

To avoid TS from complaining I'll suggest initializing it like this:

@Input() customer: Customer | null = null;

Using null will stop the compiler from complaining when you pass the input through the async pipe (the async pipe returns something like T | null).

Also by doing that you'll have to make sure that you account for null values wherever you use that property, so fewer errors to deal with in production if something goes wrong let's say.

about 4 years ago · Juan Pablo Isaza Relatório
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