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

166
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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