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

时间:2018-09-08 05:22:07

标签: angular angular6 angular-validation

我在输入字段中有一个类型为required和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>

1 个答案:

答案 0 :(得分:1)

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

用您的表单向您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)])
    });
  }

带走它可以增强并适应您的需求。