0

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

  • if `viewName` is undefined, `foobar` cannot be rendered. are you sure the `viewName` is undefined at first? – critrange Jul 12 '20 at 16:29
  • 100% certain. That is what is strange. When I debug, I can see viewName defined in the parent component right before foobar initializes. It is defined in the parent and is evaluated in the ngIf but when foobar initializes the first time, it is undefined., – Herb Patterson Jul 12 '20 at 16:37
  • can you put it on stackblitz? – critrange Jul 12 '20 at 16:38

0 Answers0