Angular 14 if statement refactor

I have the following code:

public selectionChange(value: any): void {
let commodityDescription = '';
if (!value) { 
  this.loadForm.patchValue({
    commodityDescription: commodityDescription
  });
  return; 
}

if (this.initialFormValue.commodityId === value.commodity.commodityId) {
  commodityDescription = this.initialFormValue.commodityDescription;
} else {
  commodityDescription = value.commodity.description;
}

this.loadForm.patchValue({
  commodityDescription: commodityDescription
});
}

and I don’t like having the patchValue statement in there twice. I’m trying to find a way to refactor the method so that it’s only called once. Been playing with a switch statement but can’t get it to work.

>Solution :

Change the first if to cover the others

public selectionChange(value: any): void {
    let commodityDescription = '';
    if (value) {  
      if (this.initialFormValue.commodityId === value.commodity.commodityId) {
        commodityDescription = this.initialFormValue.commodityDescription;
      } else {
        commodityDescription = value.commodity.description;
      }
    }

    this.loadForm.patchValue({
      commodityDescription: commodityDescription
    });
}

Leave a Reply