Using Angular 9, I have a child component where the ngOnInit function is called twice. The first time, some of the @Inputs are undefined and the second time, all @Inputs are properly initialized. The component renders on the second time.
Here is the setup: The parent component nests a child component . We use a boolean flag foobarDataReady to control when the foobar component initializes. I subsequently added a check for viewName - this is the @Input that is undefined on the first ngOnInit invocation.
<div *ngIf="foobarDataReady && viewName>
<foobar #foobarForm [ctxObject]="ctxObject" [typeName]="'Dog'" [viewName]="'DogView'" </foobar>
</div>
Here is the foobar component:
export class FooBarComponentimplements OnInit {
@Input() public viewName: string;
@Input() public typeName: string;
@Input() public ctxObject: any;
constructor() {}
ngOnInit() {
console.log("ngOnInit ctxObject", this.ctxObject);
console.log("ngOnInit typeName", this.typeName);
console.log("ngOnInit viewName", this.viewName);
}
The component fires this way:
When foobarDataReady is true: ngOnInit 1 - ctxObject is populated - typeName is populated - viewName is undefined - Component does not render but no errors ngOnInit 2 - ctxObject is populated - typeName is populated - viewName is populated - Component renders
Any ideas? typeName and viewName are constants and defined and set the exact same way. Even with viewName in the ngIf condition for the component, it still is undefined on the first invocation if ngOnInit.
Any ideas of how I can debug this? I've looked for malformed code and have done debug traces through the javascript with Chrome DevTools without noticing anything strange