angular mat-option using getter results in infinite loop

265 Views Asked by At

I'm using angular material select to display a dropdown in my app, when the data is provided from a parent using a getter, it causes an infinite loop, I can't find the source of resetting the input options,

an example

Will appreciate any help,

I remarked the mat-option elements and it solved the issue, I assume it causes resetting the data somehow or triggering change detection

2

There are 2 best solutions below

3
On

The main problem here is that you are passing the getter to the child component. Instead you should build an array using your getter from the parent component and then send the variable to your child component.

Parent component:

@Component({
  selector: 'app-parent',
  template: `
    <app-child [options]="parsedBusiness"></app-child>
  `,
})
export class ParentComponent implements OnInit {
   @Input() businesses: any;
   parsedBusiness: any[] = [];

   ngOnInit() {
     this.parsedBusiness = this.options;
   }

   get options() {
     return this.businesses.map((business) => ({
       value: business.id,
       label: business.name,
     }));
  }
}

This way the getter will only be executed once

0
On

A getter is executed several times along the life of the component.

As The map() method creates a new array, when you're using a mat-select makes the infinite loop the ngChanges.

You can solve using a setter in your input (I don't know if it's you're looking for), so in your parent

  options:any[]=[]
  @Input('businesses') set _(value:any[]){
     this.options=value.map(business => ({
      value: business.id,
      label: business.name
    }));
  }