Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!