angular 5个模板表单检测表单有效性状态的变化
angular 5 template forms detect change of form validity status
是reactive forms为了让组件能够侦听其包含的表单的有效性状态的变化并执行某些组件的方法的方法吗?
像[disabled]="#myForm.invalid"
一样使用templateRef很容易禁用模板中的提交按钮,但这不涉及组件的逻辑。
正在看template forms' doc没找到方法
您可以订阅整个表单更改并在那里实现您的逻辑。
@ViewChild('myForm') myForm;
this.myForm.valueChanges.subscribe(data => console.log('Form changes', data));
如果你只想得到 status
而不是 value
你可以使用 statusChanges
:
export class Component {
@ViewChild('myForm') myForm;
this.myForm.statusChanges.subscribe(
result => console.log(result)
);
}
如果您甚至想要更改数据,您可以订阅 form
的 valueChanges
并使用 this.myForm.status
:
检查表单的状态
export class Component {
@ViewChild('myForm') myForm;
this.myForm.valueChanges.subscribe(
result => console.log(this.myForm.status)
);
}
状态的可能值为:VALID、INVALID、PENDING 或 禁用。
您可以做这样的事情来检测有效性更改并根据表单是 VALID
还是 INVALID
执行方法。
this.myForm.statusChanges
.subscribe(val => this.onFormValidation(val));
onFormValidation(validity: string) {
switch (validity) {
case "VALID":
// do 'form valid' action
break;
case "INVALID":
// do 'form invalid' action
break;
}
}
我可能会迟到,但@Viewchild('anything') 可能会导致这个错误
Cannot read properties of undefined (reading 'statusChanges')
Cannot read properties of undefined (reading 'valueChanges')
您只需订阅表格即可。代码示例:
form:FormGroup;
ngOnInit(){
this.form.valueChanges.subscribe((result: any) =>
console.log('values changes here') );}
是reactive forms为了让组件能够侦听其包含的表单的有效性状态的变化并执行某些组件的方法的方法吗?
像[disabled]="#myForm.invalid"
一样使用templateRef很容易禁用模板中的提交按钮,但这不涉及组件的逻辑。
正在看template forms' doc没找到方法
您可以订阅整个表单更改并在那里实现您的逻辑。
@ViewChild('myForm') myForm;
this.myForm.valueChanges.subscribe(data => console.log('Form changes', data));
如果你只想得到 status
而不是 value
你可以使用 statusChanges
:
export class Component {
@ViewChild('myForm') myForm;
this.myForm.statusChanges.subscribe(
result => console.log(result)
);
}
如果您甚至想要更改数据,您可以订阅 form
的 valueChanges
并使用 this.myForm.status
:
export class Component {
@ViewChild('myForm') myForm;
this.myForm.valueChanges.subscribe(
result => console.log(this.myForm.status)
);
}
状态的可能值为:VALID、INVALID、PENDING 或 禁用。
您可以做这样的事情来检测有效性更改并根据表单是 VALID
还是 INVALID
执行方法。
this.myForm.statusChanges
.subscribe(val => this.onFormValidation(val));
onFormValidation(validity: string) {
switch (validity) {
case "VALID":
// do 'form valid' action
break;
case "INVALID":
// do 'form invalid' action
break;
}
}
我可能会迟到,但@Viewchild('anything') 可能会导致这个错误
Cannot read properties of undefined (reading 'statusChanges')
Cannot read properties of undefined (reading 'valueChanges')
您只需订阅表格即可。代码示例:
form:FormGroup;
ngOnInit(){
this.form.valueChanges.subscribe((result: any) =>
console.log('values changes here') );}