【问题标题】:Angular 11 reactive from error validation doesn't work来自错误验证的 Angular 11 反应性不起作用
【发布时间】:2021-06-05 11:01:33
【问题描述】:

我是 Angular 的新手。我正在尝试通过实践来学习它。我尝试了反应式表单验证,如下所示。它不起作用。我看不出有什么问题:-

TS:-

export class LoanTypesComponent implements OnInit {

addLoanTypesForm!: FormGroup;

constructor(private fb: FormBuilder) { }

ngOnInit(): void {
  this.addLoanTypesForm =   this.fb.group({
      'loanName' : new FormControl('', [Validators.required,
      Validators.maxLength(10), Validators.minLength(4)]),
      'loanType' : new FormControl('', Validators.required),
      'terms' : new FormControl(),
      'loanDescription' : new FormControl()

  });
}
}

HTML:-

  <form [formGroup]="addLoanTypesForm">

<div class="form-group">
  <input type="text" formControlName="loanName"> <br/>
  <div class="text-danger" *ngIf="addLoanTypesForm.get('loanType')?.hasError('minlength') && addLoanTypesForm.get('loanType')?.touched  ">This field minLength is 4 </div>
  <div class="text-danger" *ngIf="addLoanTypesForm.get('loanType')?.hasError('maxlength') && addLoanTypesForm.get('loanType')?.touched  ">This field max length is 10 </div>
  <div class="text-danger" *ngIf="addLoanTypesForm.get('loanType')?.hasError('required') && addLoanTypesForm.get('loanType')?.touched  ">This field is required </div>
</div>
<input type="text" formControlName="loanType"> <br/>
<div *ngIf="addLoanTypesForm.get('loanType')?.hasError('required') && addLoanTypesForm.get('loanType')?.touched  ">This field is required </div>
<input type="checkbox" formControlName="terms"> Accept Terms! <br/>
<textarea fromControlName="loanDescription"></textarea><br/>
<button [disabled]="!addLoanTypesForm.valid" (click)="addLoanType()">Add Loan</button>

我总是只有一个错误此字段为必填项。对于最小和最大长度验证永远不会显示。由于我的提交按钮在 from 有效之前被禁用,我可以看到按钮保持禁用状态,直到我满足条件。但是验证消息永远不会显示。我的代码有什么问题?

【问题讨论】:

    标签: angular validation


    【解决方案1】:

    正如之前的评论者所写:“当您在 UI 中创建验证消息时,您将它的 loanType 与 loanName 混淆了”

    解决办法是:

    <div class="text-danger" *ngIf="addLoanTypesForm.get('loanName')?.hasError('minlength') && addLoanTypesForm.get('loanName')?.touched  ">This field minLength is 4 </div>
    <div class="text-danger" *ngIf="addLoanTypesForm.get('loanName')?.hasError('maxlength') && addLoanTypesForm.get('loanName')?.touched  ">This field max length is 10 </div>
    <div class="text-danger" *ngIf="addLoanTypesForm.get('loanName')?.hasError('required') && addLoanTypesForm.get('loanName')?.touched  ">This field is required </div>
    

    如果您不想手动处理错误消息,我有一个很棒的软件包:https://www.npmjs.com/package/ngx-form-validations

    试试吧,希望喜欢。

    【讨论】:

      【解决方案2】:

      因为loanType 只有required 验证。 loanName 具有 minmax 验证。如果选中addLoanTypesForm.get('loanName') 而不是addLoanTypesForm.get('loanType'),它将正常工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-15
        • 2021-02-02
        • 2019-01-26
        • 2019-01-13
        • 2020-09-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多