在ngrx成功执行操作后,如何清理表单?

我有一个反应形式:

const createFormGroup = (dataItem?: Usuario) => {
  if (dataItem) {
    return new FormGroup({
      id: new FormControl(dataItem.id),
      nome: new FormControl(dataItem.nome),
      cidade: new FormControl(dataItem.cidade)
    });
  }
  return new FormGroup({
    id: new FormControl(),
    nome: new FormControl(''),
    cidade: new FormControl('')
  });
};

这是我的模板:

<form (ngSubmit)="save()" [formGroup]="formGroup">
   <input formControlName="nome" type="text" class="form-control" id="inputName" placeholder="Nome">
   <input formControlName="cidade" type="text" class="form-control" id="exampleInputPassword1"
   <button id="my-element" type="submit" class="btn btn-primary">Complete
   </button>
</form>

单击“提交”后,我将执行分配,使用ngrx效果保存数据:

save() {
  const user = this.formGroup.value;
  if (user.id === null) {
    this.store.dispatch(createUser({ user: user }));
  } else {
    this.store.dispatch(updateUser({ user: user }));
  }
}

这是我的效果:

public saveUser$ = createEffect(() =>
  this.actions$.pipe(
    ofType(createUser),
    switchMap((action) =>
      this.usuarioService.save(action.user).pipe(
        map(() => loadUsers()),
        catchError((error) => of(loadUsers()))
      )
    )
  )
);

当我的效果没有达到catchError时,有人可以告诉我是否有一种方法来清除我的反应性吗?

评论
dquis
dquis

You can use this.formGroup.reset() in order to clean the data from that reactive form.

If you need to reset only particular fields you can use this.formGroup.patch() as well.

Eg:- you need to reset only nome and cidade fields. Then you can use this.

this.formGroup.patch(
 {
   nome: null,
   cidade:null
 }
)

要么

this.formGroup.controls['nome'].reset();
this.formGroup.controls['cidade'].reset();
点赞
评论
普以晴
普以晴

使用This.formGroup.reset()根据要清除表单值的条件重置表单

点赞
评论
对不起
对不起
  • 如果您想以ngrx的方式执行此操作,请从您对成功的影响中调用另一个动作。
saveUser$ = createEffect(() =>
    this.actions$.pipe(
        ofType(createUser),
        switchMap((action) =>
            this.usuarioService.save(action.user).pipe(
                map(() => {
                    loadUsers();
                    return new clearFormAction();
                }),
                catchError((error) => of(loadUsers()))
            )
        )
    )
);
  • Reset your form data to empty(initial state in general cases) in the reducer for clearFormAction().
case clearFormAction: {
    return {
        ...state,
        id: '',
        nome: '',
        cidade: ''
    };
}
  • 订阅组件ngOnInit()中的商店表单数据
this.storeFormData$ = this.store.select(formData);
this.storeFormData.subscribe(formData => {
    this.formGroup.setValue(formData);
});
  • So whenever your this.usuarioService.save() is success your form will be cleared.
点赞
评论