反应式表单验证器在 Angular 中不起作用

reactive form validator won't work in Angular

我在我的输入字段中有一个所需类型和 maxLength 的验证器,我正试图在我的 HTML 上使用最干净的代码。我尝试执行以下操作但行不通

HTML

(这行不通)

<form [formGroup]="creditCardForm">
      <input type="text" pInputText formControlName="cardHolderName" required maxlength #cardHolderName/>
            <label *ngIf="form.cardHolderName.invalid &&
            (form.cardHolderName.dirty || form.cardHolderName.touched)" class="invalidField">Cardholder name is required</label>
</form>

TS

form = this.buildCreditCardForm(this.fb).controls;
.
.
buildCreditCardForm(fb: FormBuilder): FormGroup {
   return fb.group({
      cardHolderName: ['', [Validators.required, Validators.maxLength(50)]],
    .
    .
}

HTML(这个可以,但是太长了,脏了)

<form [formGroup]="creditCardForm">
<input type="text" pInputText formControlName="cardHolderName" required maxlength #cardHolderName/>
        <label *ngIf="fcreditCardForm.controls.cardHolderName.invalid &&
        (creditCardForm.controls.cardHolderName.dirty || creditCardForm.controls.cardHolderName.touched)" class="invalidField">Cardholder
          name is required</label>
</form>

您混合了反应式验证器和模板验证器。不确定为什么要使事情复杂化,反应形式很简单。

用你的表格给你一个 Demo:

HTML:

<form [formGroup]="creditCardForm">
    <input type="text" formControlName="cardHolderName"/>
    <label *ngIf="creditCardForm.get('cardHolderName').invalid">Cardholder name is required</label>
</form>

分量:

  creditCardForm;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.creditCardForm = new FormGroup({
      'cardHolderName': new FormControl(null, [Validators.required, Validators.maxLength(5)])
    });
  }

带走它,根据您的需要进行增强和调整。