【问题标题】:Angular: Can't bind to 'ngModelOptions' since it isn't a known property of 'input'Angular:无法绑定到“ngModelOptions”,因为它不是“输入”的已知属性
【发布时间】:2018-12-20 18:40:08
【问题描述】:

我的验证有问题。我想为我的电子邮件输入添加验证,但我收到错误“无法绑定到 'ngModelOptions',因为它不是 'input' 的已知属性”。

添加组件.html

<form name="form" [formGroup]="form" (ngSubmit)="form.valid" class="form">
<mat-form-field>
    <input matInput
           placeholder="Adres e-mail"
           formControlName="email"
           [(ngModel)]="employee.email"
           [ngModelOptions]="{standalone: true}"
           [ngClass]="{'is-invalid':form.get('email').touched && form.get('email').invalid}"
           type="email"
           required>
           <div *ngIf="form.get('email').touched && form.get('email').invalid"  class="invalid-feedback">
              <div *ngIf="form.get('email').errors.required">Email Name is required</div>
              <div *ngIf="form.get('email').errors.email">Email must be a valid email Address</div>
           </div>
  </mat-form-field>

add-component.ts

form = new FormGroup({
    email: new FormControl('', [
      Validators.required,
      Validators.email
    ])
  });

我已经在 app.module.ts 中包含了 FormsModule、ReactiveFormsModule。

【问题讨论】:

标签: angular validation angular-material


【解决方案1】:

AngularJS 以来,Angular 中的 ngModelOptions 指令已更改。许多功能以角度删除。来自角度文档:

跟踪此 ngModel 实例的配置选项。

name:在表单控件元素上设置名称属性的替代方法。请参阅使用 NgModel 作为独立控件的示例。

standalone:当设置为 true 时,ngModel 将不会在其父表单中注册自己,并且就像它不在表单中一样。默认为 false。

updateOn:定义表单控件值和有效性更新的事件。默认为“更改”。可能的值:'改变' | '模糊' | '提交'。

Angular 的验证方式是使用 FormControl:

emailFormControl = new FormControl('', [
  Validators.required,
  Validators.email,
]);

你可以在这个DEMO看到

已编辑,感谢@ConnorsFan 的评论。

【讨论】:

  • 请注意ngModelOptions 也是ngModel 指令的输入属性(参见the documentation)。
猜你喜欢
  • 2019-03-23
  • 1970-01-01
  • 2017-11-18
  • 2020-11-19
  • 2016-12-18
  • 2016-12-17
  • 1970-01-01
  • 2018-04-23
  • 2017-11-30
相关资源
最近更新 更多