【问题标题】:angular2 form validation: get an instance of ngFormangular2 表单验证:获取 ngForm 的实例
【发布时间】:2017-10-02 04:51:55
【问题描述】:
如何在组件中引用“myform”?可能吗?
必须使用表单生成器(我试图避免使用它)?
<form #myForm="ngForm">
<label class="col-sm-12" [class.ng-invalid]="!(value.valid || Value.pristine)">Value</label>
<input type="text" required ngControl="value" #value="ngForm" class="form-control text-center" [(ngModel)]="value" />
</form>
【问题讨论】:
标签:
angular
angular2-forms
【解决方案1】:
实际上还有另一种方法可以做到这一点。你可以使用 ViewChild 注释,这里你的例子适应了:
<form #myForm="ngForm">
<label class="col-sm-12" [class.ng-invalid]="!(value.valid || Value.pristine)">Value</label>
<input type="text" required ngControl="value" #value="ngForm" class="form-control text-center" [(ngModel)]="value" />
class MyForm {
@ViewChild('myForm') form;
ngAfterViewInit() {
console.log(this.form)
this.form.control.valueChanges
.subscribe(values => console.log(values));
}
}
【解决方案2】:
为此,您需要改用FormBuilder 类和ngFormModel 指令。 ngForm 和 ngControl 在线获取内联表单。
这是一个示例:
<form [ngFormModel]="myForm">
<label class="col-sm-12"
[class.ng-invalid]="!(myForm.controls.value.valid || myForm.controls.value.pristine)">Value</label>
<input type="text" [ngControlControl]="myForm.controls.value"
class="form-control text-center" [(ngModel)]="value" />
</form>
在组件类中:
@Component({
(...)
})
export class SomeComponent {
constructor() {
this.myForm = builder.group({
value: ["", Validators.required],
})
}
}
查看这篇文章了解更多详情: