How to run "valueChanges" programmatically?

On one of my pages I use FormBuilderto fill out a form during initialization. Each input gets a class when the input is not empty. This is done by adding ngClassto each entry and subscribing to FormGroup valueChanges.

My problem occurs whenever a form is populated programmatically. Whenever the user changes any form value, the call valueChangesis called, however, this is not the case when it is used FormBuilder.

My question is how to get an event valueChangesthat will be fired when it ends FormBuilder.

I tried to use this.FormGroup.updateValueAndValidity(), but it didn’t lead to anything.

+15
source share
3 answers

I found a solution that worked for me. I forgot two parameters in the function updateValueAndValidity.

  • onlySelf: will update this FormControlwhen true.
  • emitEvent: will trigger an event valueChangeswhen it is true.

Thus, as a result, you get something like: FormGroup.updateValueAndValidity({ onlySelf: false, emitEvent: true });

+17
source

Your question is not 100% clear, but I think you say:

My valueChanges works great when changing anything in the user interface, but I want to call the logic of my subscription function as soon as I finish initializing the FormBuilder object in my constructor to handle the initial conditions.

In this case, what I'm doing is pretty simple:

    this.searchForm.valueChanges
        .pipe(startWith(initialValues)).subscribe(value =>
        {
            // whatever you want to do here
        });

initialValues - , . , , searchForm.getRawValue() .

, .

+6

. ? ()

  • ?
  • , valueChanges ?

, Plunkr: https://plnkr.co/edit/4V4PUFI1D15ZDWBfm2hb?p=preview

, :

this.myForm.get('myField').setValue(newValue);

, valueChanges, . , , .

dirty ( : " , " ). , dirty, , , , dirty, ?

(i) . valueChanges . .

+2

Source: https://habr.com/ru/post/1015242/


All Articles