我希望在表格有效时自动保存内容,而不点击保存按钮。
答案 0 :(得分:3)
您需要订阅FormGroup的statusChanges()
方法,并且在该Observable中,您可以确定FormGroup是否有效,然后触发保存事件。
import 'rxjs/add/operator/takeWhile';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({...})
export class MyComponent {
private form: FormGroup;
private alive: boolean;
constructor(private formBuilder: FormBuilder) {}
public ngOnInit(): void {
this.alive = true;
this.form = this.formBuilder.group({
// your form configuration
});
this.form.statusChanges()
.takeWhile(this.alive) // only subscribe while this component is alive
.subscribe((status) => {
// if status is valid, auto-save
});
}
public void ngOnDestroy() {
this.alive = false;
}
}
答案 1 :(得分:1)
不要忘记最后取消订阅。您应该捕获您的订阅并在最后取消订阅它们。避免任何内存泄漏。
import { Subscription } from 'rxjs/subscription';
@Component({...})
export class MyComponent {
...
subscription = new Subscription;
...
ngOnInit() {
this.subscription.add(this.form.statusChanges()
.takeWhile(this.alive)
.subscribe(status => {
//do whatever
});
ngOnDestroy() {
this.subscription.unsubscribe();
}
答案 2 :(得分:0)
如果您具有异步验证器,则以下选项仅在执行验证器且未报告任何错误之后才会保存表格
formControl.statusChanges
.pipe(
filter((status) => status === 'VALID'),
withLatestFrom(formControl.valueChanges),
map(([_status, value]) => value),
switchMap(value=>this.service.save(value)) // if you are using a service
takeUntil(this.destroy$)
)
.subscribe((value) => {
//if you've been using NGRX for example
this.store.dispatch(action)
});