问题
I have a reactive form which uses a validator to control the length of the input.
I would like to read that length back again in the template so that I can guide the user as to what the maximum length actually is but I can't figure out how to read it from the form.
Is that possible?
// 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
What is the correct way to read this maxLength back out of the FormControl object?
[edit for clarity] I want to read the value out before the user has created the error, not afterwards. This is for telling them what their allowance is rather than that they have an issue.
I'd also like to avoid using a separate variable in order to keep code minimal.
回答1:
It should be like this :
 <mat-hint *ngIf="investorForm.hasError('maxlength', 'name')">
  Max length: {{ investorForm.get('name').errors.maxlength.requiredLength }}</mat-hint>
You must be setting the value of maxLength either hard coded or  from a constant file. you can store the limit into a variable and then use in the view. i.e :
in 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)]],
    })
  }
in component.html :;
<small> max allowed length is :  {{maxLen}} </small>
Demo
来源:https://stackoverflow.com/questions/61393478/how-do-you-read-the-value-of-a-maxlength-validator-so-that-you-can-print-it-into