是否有事件可以知道表格何时有效?
Is there an event to know when a form is valid?
我正在使用 FormGroup
、自定义验证器等。当表单变为 valid/invalid 时,我需要在事件处理程序中捕获,而不是 属性,而是在打字稿代码。
我查看了文档,但找不到类似的内容:(validityChange)="myEventHandler($event)"
其中 validityChange
只是我要查找的实际事件名称的占位符。
订阅statusChanges
this.myForm.statusChanges
.filter(s => s == 'VALID')
.subscribe(val => onValid())
借鉴 @Gunter 的 , but utilizing the current API you can simplify it and drop the usage of the 'VALID'
constant from your code by using the valid
属性:
this.myForm.statusChanges
.filter(() => this.myForm.valid)
.subscribe(status: string => onValid());
顺便说一句,根据此订阅是否会导致内存泄漏,从中 do not forget 到 unsubscribe()
。
对于使用 RxJs 6+ 的 Angular(您需要使用管道的地方):
this.form.statusChanges
.pipe(
filter(() => this.form.valid))
.subscribe(() => this.onFormValid());
this.form.valid
是一个 属性 ,它是布尔值,因此要么为真,要么为假。因此,当表单有效时过滤器将 return 为真,然后订阅将仅在 属性 为真时调用 this.onFormValid()
。
你可以通过这样做看到发生了什么:
public ngOnInit() {
this.form.statusChanges
.pipe(
filter((status: string) => {console.log(status); return this.form.valid}))
.subscribe(() => this.onFormValid());
}
private onFormValid() {
console.log('form is valid')
}
一个也应该(完整),例如:
this.form.statusChanges
.pipe(
filter(() => this.form.valid)),
takeUntil(this.destroy$)
.subscribe(() => this.onFormValid());
ngOnDestroy() {
this.destroy$.next();
}
我正在使用 FormGroup
、自定义验证器等。当表单变为 valid/invalid 时,我需要在事件处理程序中捕获,而不是 属性,而是在打字稿代码。
我查看了文档,但找不到类似的内容:(validityChange)="myEventHandler($event)"
其中 validityChange
只是我要查找的实际事件名称的占位符。
订阅statusChanges
this.myForm.statusChanges
.filter(s => s == 'VALID')
.subscribe(val => onValid())
借鉴 @Gunter 的 'VALID'
constant from your code by using the valid
属性:
this.myForm.statusChanges
.filter(() => this.myForm.valid)
.subscribe(status: string => onValid());
顺便说一句,根据此订阅是否会导致内存泄漏,从中 do not forget 到 unsubscribe()
。
对于使用 RxJs 6+ 的 Angular(您需要使用管道的地方):
this.form.statusChanges
.pipe(
filter(() => this.form.valid))
.subscribe(() => this.onFormValid());
this.form.valid
是一个 属性 ,它是布尔值,因此要么为真,要么为假。因此,当表单有效时过滤器将 return 为真,然后订阅将仅在 属性 为真时调用 this.onFormValid()
。
你可以通过这样做看到发生了什么:
public ngOnInit() {
this.form.statusChanges
.pipe(
filter((status: string) => {console.log(status); return this.form.valid}))
.subscribe(() => this.onFormValid());
}
private onFormValid() {
console.log('form is valid')
}
一个也应该
this.form.statusChanges
.pipe(
filter(() => this.form.valid)),
takeUntil(this.destroy$)
.subscribe(() => this.onFormValid());
ngOnDestroy() {
this.destroy$.next();
}