Home > Back-end >  Angular 14 if statement refactor
Angular 14 if statement refactor

Time:01-18

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.

CodePudding user response:

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
    });
}

CodePudding user response:

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

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