user1797508
user1797508

Reputation: 292

Angular Forms: after a patchValue unable to type in field

I have a form that I am toggling from a data-table. When I pre-fill the form using patchValue, I am unable to edit the contents of the field. Fields that are not filled with patchValue are updatable.

Here is the Controller set-up

@Input() signalMutate: Signal;

  signalForm: FormGroup;
  loading = false;
  submitted = false;
  error: string;
  formSignalValue: Signal;

  constructor(
    private formBuilder: FormBuilder,
    private router: Router,
    private authenticationService: AuthenticationService,
    private userService: UserService

  ) { }

  ngOnInit() {
    this.signalForm = this.formBuilder.group({
      title: [''],
      description: ['', Validators.required],
      problem: ['', Validators.required],
      value: ['', Validators.required],
      requestor: ['', Validators.required],
      label: ['']
  });


  }

  ngAfterContentChecked(){

    if(this.signalMutate) { 

        this.signalForm.patchValue(this.signalMutate);

    }

  }

Any idea why this is happening?

Thanks!

Upvotes: 0

Views: 814

Answers (1)

bryan60
bryan60

Reputation: 29335

Because you're doing it in the afterContentChecked hook which runs on every change detection cycle, and change detection triggers everytime you type in an input, so you just keep resetting the value to whatever signalMutate is everytime you type.

do this:

private _signalMutate: Signal;
@Input() set signalMutate(signalMutate: Signal) {
  this._signalMutate = signalMutate
  this.signalForm.patchValue(signalMutate);
}
get signalMutate() {
  return this._signalMutate
}

setter inputs run when the input changes. This set up will also require you to make sure that you don't ever mutate the signal object you pass in if you want the changes to be reflected in the form. Make sure you always create a new object like:

this.signal = {...this.signal, ...newSignal }

avoiding object mutation like this is generally considered good practice in any event, increases app performance, and helps avoid hard to find bugs (like this)

Upvotes: 5

Related Questions