'Angular 11 Form PatchValue/SetValue is not working sometimes

There's only one input in my form that sometimes initialize correctly, other times it doesn't.

<p-dropdown [placeholder]="'Grupo de movimentação' | translate" [options]="movementGroupOptions" name="movementGroup" optionLabel="label" formControlName="movementGroup"  datakey="id">
  <ng-template let-movementGroup pTemplate="item">
     <div style="display: flex; align-items: center;">
       <img [src]="movementGroup.value.iconUrl" style="width: 20px; margin-right: 5px;" />
       <span>{{movementGroup.value.name}}</span>
     </div>
  </ng-template>
  <ng-template pTemplate="selectedItem">
     <div style="display: flex; align-items: center;">
        <img [src]="boatForm.get('movementGroup').value.iconUrl" style="width: 20px; margin-right: 5px;" />
        <span>{{boatForm.get('movementGroup').value.name}}</span>
     </div>
  </ng-template>
</p-dropdown>

This is my function that should set the form values:

setBoatForm(): void {
    Object.keys(this.boatForm.controls).forEach((key) => {
      if (
        this.boat[key] &&
        this.boatForm.get(key) &&
        this.boatForm.get(key).enabled
      ) {
        if (key === 'boatCustomers') {
          this.boat[key]
            .filter((b) => b.type === CustomerType.Owner)
            .forEach((b) => {
              this.addCustomer(b);
            });
          this.boat[key]
            .filter((b) => b.type !== CustomerType.Owner)
            .forEach((b) => {
              this.addAssociated(b);
            });
        }
        if (key === 'boatServices') {
          this.boat[key].forEach((s) => {
            this.associateServiceBoat(s);
          });
        }
        this.boatForm.get(key).patchValue(this.boat[key]);
      }
    });
  }

But the main issue is that, if I run a console.log(this.boatForm.get('movementGroup'), at the end of the ngOnInit() function, it would return the correct object, everytime... But sometimes the form itself is not populated



Solution 1:[1]

You should call html references when the page fully loaded . ngAfterViewInit life cycle hooks will be triggered when template fully loaded so You should call your function inside it:

ngAfterViewInit(){
console.log(this.boatForm.get('movementGroup')

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zrelli Majdi