如果作者字段未绑定条件,则进行角度形式验证。
角度7
HTML:
<div class="form-group">
<label class="col-md-4">Author Name </label>
<input type="text" class="form-control" formControlName="author" #author /></div>
<div *ngIf="author.invalid && (author.dirty || author.touched)" class="alert alert-danger">
<div *ngIf="author.errors.required">
Author is required.
</div>
</div>
TS:
import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';
bookForm = new FormGroup({author: new FormControl('', Validators.required)});
get author() {
return this.bookForm.get('author');
}
答案 0 :(得分:0)
尝试这种情况
bookForm.get('author').touched && bookForm.get('author').invalid &&
bookForm.get('author').errors.required
答案 1 :(得分:0)
从输入HTML元素中删除#author
,因为它的Template Variables
不具有invalid
,touched
等属性。
模板变量:
模板引用变量通常是对模板中DOM元素的引用。它也可以是对Angular组件或指令或Web组件的引用。
使用井号(#)声明参考变量。 #phone在元素上声明了一个电话变量。
答案 2 :(得分:0)
如果FormControl
有效,则errors
字段将返回undefined
。因此,您只能使用*ngIf="author.errors"
。如果您想在错误且无效的情况下显示错误,可以使用以下方法:
<div *ngIf="author.dirty && author.errors" class="alert alert-danger">
<ng-container *ngIf="author.errors.required">
Author is required.
</ng-container>
</div>
答案 3 :(得分:0)
<form #form="ngForm" (ngSubmit)="onSubmit(form)"
[ngClass]="{'was-validated': form.invalid && (form.dirty || form.touched)}">
<div class="" ngModelGroup="User">
<h2 class="text-center">Registration page</h2>
<br />
<div class="form-group">
<input type="text" class="form-control" placeholder="First Name" name="firstname" required
ngModel #firstname="ngModel">
<span class="help-bpx" *ngIf="firstname.touched && !firstname.valid ">Please enter the
firstname</span>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Last Name" name="lastname" required ngModel
#lastname="ngModel">
<span class="help-bpx" *ngIf="lastname.touched && !lastname.valid ">Please enter the
lastname</span>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" placeholder="Email" name="email" email
required ngModel #email="ngModel">
<span class="help-bpx" *ngIf="email.touched && !email.valid ">Please enter the Email
Value</span>
</div>
<div class="form-group">
<div class="custom-file">
<input type="file" class="custom-file-input" id="customFile" required ngModel name="file" #file="ngModel">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
<br />
<div class="align-center">
<button type="submit" class="btn btn-primary" [disabled]="!form.valid">Register</button>
</div>
</div>
</form>