当密码字段有效时,我尝试使用 [angular version:13] 以反应形式启用和禁用密码字段。
我用我不喜欢的技术解决了它。
[HTML]
<input formControlName="password" (change)="enableOrDisablePassword()" type="text" >
零件
enableOrDisablePassword(){
setTimeout(()=>{
(this.form.get('password')?.valid) ?
this.form.get('repassword')?.enable():
this.form.get('repassword')?.disable();
},2000);
}
setTimeout() 是因为当您尝试检查是否有效时...... FormControl 返回以前的状态而不是新的......所以我等待它更新。
有些文章建议在 FormGroup 级别使用验证器功能,因为您正在与同一块中的两个字段进行交互。无论如何,我尝试了很多事情,但问题总是一样的......返回 value 始终是以前的状态,而不是新的。我得等一会儿。
回答1
我会使用这些方面的东西:
export class AppComponent {
// just a simple form definition with some basic validation I used
// to test this solution with
form = new FormGroup({
password: new FormControl(undefined, Validators.pattern('^[a-zA-Z0-9]{4}$')),
repassword: new FormControl(),
});
ngOnInit() {
const passCtrl = this.form.controls['password'];
const repassCtrl = this.form.controls['repassword'];
passCtrl.valueChanges.subscribe(x => {
passCtrl.valid ? repassCtrl.enable() : repassCtrl.disable();
});
}
}
@E。 Maggini 的答案有效(如果您更正 getter/method 调用位),但是因为 [disabled]
表达式在每个更改检测周期都被评估,如果该技术在页面上应用得太频繁,可能会影响性能。此外,不是 100% 肯定这一点,但我相信 Angular 不喜欢当您像这样绑定 [disabled]
并同时使用 Reactive Forms 时。
// 更新是的,Angular 不喜欢那个方法。在控制台上:
It looks like you're using the disabled attribute with a reactive form directive.
If you set disabled to true when you set up this control in your component class,
the disabled attribute will actually be set in the DOM for you. We recommend
using this approach to avoid 'changed after checked' errors.
回答2
为什么不简单地做
<input formControlName="repassword" [disabled]="isPasswordInvalid()" type="text">
get isPasswordInvalid(): boolean {
return this.form.get('password')?.valid;
}