TrevorGoodchild
TrevorGoodchild

Reputation: 1058

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.

Upvotes: 0

Views: 64

Answers (2)

Krenom
Krenom

Reputation: 2108

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

Upvotes: 1

depperm
depperm

Reputation: 10746

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

Upvotes: 1

Related Questions