0

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

Shalashka
  • 47
  • 6
  • Is your issue solved or do u still need help? – toTheBestOfMyKnowledge Aug 08 '23 at 06:51
  • @toTheBestOfMyKnowledge it isn't solved yet, using map on parent doesn't seem to make a difference, and even if so, it is not the optimal solution as the child component is a custom select component, therefore it will be better if the solution will be in child component since I cannot control how others pass data to the custom select component – Shalashka Aug 08 '23 at 07:18

2 Answers2

0

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
    }));
  }
Eliseo
  • 50,109
  • 4
  • 29
  • 67
0

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

Osakr
  • 1,027
  • 1
  • 13
  • 26
  • Thanks for answering, proving a solution in parent component isn't optimal since the child component is a custom select component, therefore it will be better if the solution will be in child component since I cannot control how others pass data to the custom select component – Shalashka Aug 08 '23 at 07:28
  • You can do the same in the child component then, on the OnInit you can transform the data in the way you want – Osakr Aug 08 '23 at 07:31
  • what if the input is updated after ngOnInit ? this won't work, – Shalashka Aug 13 '23 at 12:01