當密碼欄位有效時,我嘗試使用 [angular version:13] 啟用和禁用 **Reactive form ** 中的重新密碼欄位。
我用我不喜歡的技術解決了它。
[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級別使用驗證器功能,因為您正在與同一塊中的兩個欄位進行互動。無論如何,我嘗試了很多事情,但問題總是一樣的......回傳值始終是以前的狀態,而不是新的。我得等一會兒。
謝謝。
uj5u.com熱心網友回復:
我會使用這些方面的東西:
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.
uj5u.com熱心網友回復:
為什么不簡單地做
<input formControlName="repassword" [disabled]="isPasswordInvalid()" type="text">
get isPasswordInvalid(): boolean {
return this.form.get('password')?.valid;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/477809.html
