在表單組驗證中,我嘗試應用輸入最大長度,但是,此最大長度取決於表單中的其他操作。如果他們改變,也改變maxMsgLength屬性的值。動態更改角度2的最大長度值Validators.maxLength
MSG:[ '',Validators.maxLength(this.maxMsgLength)],
然而maxMsgLength,驗證器棒到舊maxMsgLength值的變化之後。有沒有一種方法來重新驗證這個驗證字段的新值maxLength?
代碼: class Account { maxMsgLength = 200; newAccount:FormGroup;
//activated by click on another method
private changeMaxMsgLength() : void {
let values = Object.values(this.accountsStorage);
if(values.includes("oldAccount")) {
this.maxMsgLength = 150;
} else {
this.maxMsgLength = 200;
}
}
ngOnInit(): void {
this.newAccount = this.formbuilder.group({
msg : ['', Validators.maxLength(this.maxMsglength)],
link : ['', Validators.pattern('^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$')],
schedule : ['', Validators.pattern('^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) (2[0-3]|[01][0-9]):[0-5][0-9]$')]
});
}
}
//where in template there is
<div class="form-group">
<label for="name">Message</label>
<textarea class="form-control" id="Message" formControlName="msg" style="width: 300px; height: 150px;"></textarea>
</div>
<div class="error" *ngIf="newAccount.get('msg').hasError('maxlength')">
Maximum of {{maxMsglength}} characters
</div>
而且沒有按」工作this.newAccount.controls [ 'MSG'] updateValueAndValidity() ; –