如何在Angular2中应用没有<form>标签的表单验证

use*_*088 22 angular

我想知道是否有办法在不使用标签的情况下验证Angular 2中的表单form?例如下面我想让它成为必填字段

<div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" id="name">
</div>
<button type="button" class="btn btn-default" (click)="save()">Save</button>
Run Code Online (Sandbox Code Playgroud)

Pau*_*tha 27

表单控件可以是独立的(没有父表单),无论是使用声明性表单控件还是反应式表单控件.

对于声明(使用ngModel),你可以做类似的事情

<input #model="ngModel" [(ngModel)]="value" type="text" required/>
<div *ngIf="model.invalid" style="color: red">Required</div>
Run Code Online (Sandbox Code Playgroud)

对于反应形式,你可以做类似的事情

<input [formControl]="control" [(ngModel)]="value" type="text"/>
<div *ngIf="control.invalid" style="color: red">Required</div>

// in component
this.control = new FormControl('', [Validators.required]);
Run Code Online (Sandbox Code Playgroud)

Plunker

有关一般使用Angular表单的更多信息,请参阅docs/tutorial


Joh*_*lph 10

除了直接使用表单控件,如@peeskillet在其答案中所示,您可以使用其选择器将表单指令附加到任何标记ngForm:

<div ngForm #newRuleForm="ngForm">
  <div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" id="name">
  </div>
  <button type="button" class="btn btn-default" [disabled]="!newRuleForm.valid" (click)="save()">Save</button>
</div>
Run Code Online (Sandbox Code Playgroud)

请记住,您不能使用像<button type=submit>这种情况下的标准表单功能,但是当我想使用模板驱动的表单同时保留一种简单的方法来验证一组字段时,我发现这种方法非常有价值.