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?
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.