简体   繁体   中英

NGXS <-> Angular: 2-Way binding

I want to synchronize 2 form-fields which are populated by the ngxs-form-plugin.

If i change input-field#1, store gets synced, but input-field#2 still has old value. Same happens for input-field#2

Is there a ngxs-way using Reactive-Forms to keep them in sync?

Code-example: Stackblitz.com

The issue here is not about the ngxs but only reactive forms, when you have multiple components binded to the same FormControl , when a components value changes, the reactive form takes care of changing the model value but not the other components values.

To handle this case, the only hacky way a found is to listen to the form value changes, and set the same value making sure not to dispatch the event to avoid an infinit loop.

In the shared example you can add this to the AppComponent constructor :

constructor(private fb: FormBuilder, private store: Store) {
    this.nameForm.valueChanges
     .subscribe(_ =>
      this.nameForm.setValue(_, { emitEvent: false}));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM