我有一个反应式表单,它使用一个验证器来控制输入的长度。
我想在模板中再次读取该长度,以便引导用户了解最大长度到底是多少,但我不知道如何从表单中读取它。
这可能吗?
// investor-signup.component.ts
export class InvestorSignupComponent implements OnInit {
public investorForm = this.fb.group({
name: ['', [Validators.required, Validators.maxLength(5)]],
// I want to access be able be able to print the '5' above into the form
// without having to duplicate the value or create another variable.
url: [''],
type: [''],
})
}
// investor-signup.component.html
...
<input matInput
formControlName="name"
required
placeholder="Startup Capital Inc.">
<mat-hint>Must be less than {{investorForm.name.validators.maxLength.value}} characters long</mat-hint>
// note - the investorForm.name.validators.maxLength.value above does NOT work
从FormControl对象中读回这个maxLength的正确方法是什么?
[为清晰起见编辑]我想从FormControl对象中读出这个值。之前 而不是在用户产生错误之后。这是为了告诉他们他们的津贴是多少,而不是告诉他们有问题。
我也想避免使用一个单独的变量,以保持最少的代码。
它应该是这样的。
<mat-hint *ngIf="investorForm.hasError('maxlength', 'name')">
Max length: {{ investorForm.get('name').errors.maxlength.requiredLength }}</mat-hint>
你必须设置 maxLength
你可以将限制存储到一个变量中,然后在视图中使用,即 。
在 component.ts
:
const MAX_LENGTH = 3;
testForm: FormGroup;
private maxLen = MAX_LENGTH;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.testForm = this.fb.group({
name: ['', [Validators.maxLength(this.maxLen)]],
})
}
在 component.html
:;
<small> max allowed length is : {{maxLen}} </small>