【问题标题】:Form validations with ngModel and ngModelOption in angular 8在 Angular 8 中使用 ngModel 和 ngModel 选项进行表单验证
【发布时间】:2023-04-03 18:46:01
【问题描述】:

我将 angular 8 与 formGroup 和 formController 一起用于验证,这在反应式和模板驱动的表单中效果很好。 但是,我试图在 Angular 8 中使用带有“ngModelOptions”属性的“ngModel”(这是一个动态生成的字段)。它使用“必需”属性正确显示字段级验证,但我无法阻止按钮单击或在错误验证状态下禁用“按钮”。示例代码如下:

<form [formGroup]="myForm" #form1="ngForm">
 <!-- few formControlName fields here -->
<mat-form-field>
   <input matInput [(ngModel)]="firstname" [ngModelOptions]="{standalone: true}" [placeholder]="First name" required />
   <mat-error>This field is <strong>required</strong></mat-error>
</mat-form-field>
<mat-form-field>
   <input matInput [(ngModel)]="lastname" [ngModelOptions]="{standalone: true}" [placeholder]="Last name" required />
   <mat-error>This field is <strong>required</strong></mat-error>
</mat-form-field>
<button mat-button [disabled]="!(form1.form.valid)">Submit</button>
</form>

尽管名字和姓氏字段为空白,但提交按钮永远不会被禁用。我了解当您将其标记为独立时:true 这不会发生(它不会添加到 FormGroup)。 但是是否有任何解决方法或其他方法可以实现 ngModel 验证以限制按钮上的表单提交?

【问题讨论】:

标签: angular ngmodel angular2-form-validation


【解决方案1】:

如果你放入相同的标签

<form [formGroup]="myForm" #form1="ngForm">

“form1”是myForm,“firstName”和“lastName”不属于myForm。

如果你使用

[ngModelOptions]="{standalone: true}"

您的输入不属于任何形式。

您可以在输入中添加 #firstnameID="ngModel" 和 #lastnameID="ngModel" 并询问 firstnameID.valid 和 lastnameID.valid

<form [formGroup]="myForm" #form1="ngForm">
 <!-- few formControlName fields here -->
<mat-form-field>
   <input matInput [(ngModel)]="firstname" 
        #firstnameID="ngModel"
        [ngModelOptions]="{standalone: true}" 
        placeholder="First name" required />
   <mat-error>This field is <strong>required</strong></mat-error>
</mat-form-field>
<mat-form-field>
   <input matInput [(ngModel)]="lastname" 
       #lastnameID="ngModel"
       [ngModelOptions]="{standalone: true}" 
       placeholder="Last name" required />
   <mat-error>This field is <strong>required</strong></mat-error>
</mat-form-field>
<button mat-button [disabled]="!(myForm.valid) ||
                               !firstnameID.valid ||
                               !lastnameID.valid">Submit</button>
</form>

注意:我想这不是您期望的答案,但它是这样的

【讨论】:

  • 模板驱动表单验证遵循这种模式,将模板变量分配给与 ngModel 绑定的输入,并且该引用可用于添加验证(有效、原始等)。
  • 考虑到我要求同时具有 fonrControlName 和 ngModelOptions,这看起来是一个很好的解决方案。谢谢!
  • 你如何处理 ngFor ?例如,地址的联系人列表。仅当数组中的所有控件都有效时,才必须启用按钮
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 2016-05-24
  • 2017-03-07
  • 2018-02-17
  • 1970-01-01
相关资源
最近更新 更多