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

169
Visualizações
Rendering angular component conditionally based on its input variable doesn't infer the existence of the input variable

I have an angular component with an array of Input variables that is asynchronously initialized in the parent.

@Component({ ... })
export class ChildComponent {
  @Input inputVariable: string;
}
@Component({ ... })
export class ParentComponent implements OnInit {
  inputVariables: string[] = [];

  constructor( private http: HttpClient ) { }

  ngOnInit(): void {
    this.http.get<string[]>('someUrl')
      .subscribe(res => this.inputVariables = res)
  }
}

Now I want to render in parent.component.html a ChildComponent for each inputVariable like this:

<div *ngFor="let inputVariable of inputVariables">
  <child-component [inputVariable]="inputVariable" />
</div>

In ChildComponent I can be sure that inputVariable is defined. However, typescript complains, that the type of inputVariable must be string | undefined. However, then I need to check in every usage of inputVariable in ChildComponent whether inputVariable is defined or not, which is not, what I want to do.

Is there a solution for ts to infer, that inputVariable always is defined for any rendered ChildComponent?

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

0

Value for @Input is set later than on initialisation (on ngOnInit hook to be precise). To stop typescript from complaining, just set the default value for inputVariable like that:

@Component({ ... })
export class ChildComponent {
  @Input inputVariable: string = "";
}

It tells you to set type to string | undefined, because the default value of every variable in javascript is undefined. Giving it the default value of empty string, you don't have to worry about different types.

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