[英]How to validate template driven form without model driven approach.?
I am trying to validate template driven form in Angular without two way databinding. 我正在尝试在没有两种方式的数据绑定的情况下在Angular中验证模板驱动的表单。 I have done validation using [(ngModel)]
but when i try to validate form without MODEL i get following error 我已经使用[(ngModel)]
完成了验证,但是当我尝试不使用MODEL来验证表单时,出现以下错误
Cannot read property 'invalid' of undefined 无法读取未定义的属性“无效”
This is my HTML code. 这是我的HTML代码。
<div class="jumbotron">
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<h3>Angular 6 Template-Driven Form Validation</h3>
<form name="form" (ngSubmit)="onSubmit(f.value)" #f="ngForm" novalidate>
<div class="form-group">
<label for="username">Username:</label>
<input type="text"
class="form-control"
name="username"
#userName
required
minlength="8"/>
<div *ngIf="f.form.controls.username.invalid && f.form.controls.username.touched" class="invalid-feedback">
<div *ngIf="f.form.controls.username.errors.required" class="alert alert-danger">Username is required</div>
<div *ngIf="f.form.controls.username.minlength" class="alert alert-danger">length should b 8 character</div>
</div>
</div>
<button class="btn btn-primary" >Register</button>
</form>
</div>
</div>
</div>
</div>
It also not sending data to component when i click button. 当我单击按钮时,它也不向组件发送数据。
this is component TS file
. 这是组件TS file
。
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-template-driven-form',
templateUrl: './template-driven-form.component.html',
styleUrls: ['./template-driven-form.component.css']
})
export class TemplateDrivenFormComponent {
// model: any = {};
onSubmit(f) {
// alert('SUCCESS!! :-)\n\n' + f);
console.log(f);
}
}
Just replace: 只需替换:
f.form.controls.username.invalid
with 与
username.invalid
but its mandatory to use ngModel
但必须使用ngModel
so your HTML control: 因此,您的HTML控件:
<input type="text" ngModel class="form-control" name="username" #username="ngModel" required minlength="8"/>
It's not working because it shouldn't. 它不起作用,因为它不应该。
As you can see , inputs that aren't bound with ngModel
aren't part of your form. 如您所见 ,不与ngModel
绑定的输入不属于表单。
So simply use ngModel
and you should be good to go. 因此,只需使用ngModel
,您就应该做好了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.