动态更改角度2的最大长度值Validators.maxLength
问题描述:
在表单组验证中,我尝试应用输入最大长度,但是,此最大长度取决于表单中的其他操作。如果他们改变,也改变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>
答
发现了答案! :d,需要使用方法setValidators从AbstractControl:
newAccount.controls['msg'].setValidators(Validators.maxLength(this.maxMsglength))
方法overites先前验证器,并设置新的具有更新maxMsgLenth值
答
您可以使用HTML输入的maxlength
属性吧:
<input [attr.maxlength]="maxMsgLength" />
而且没有按”工作this.newAccount.controls [ 'MSG'] updateValueAndValidity() ; –