0

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.

2 Answers 2

1

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
    });
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.