响应式表单验证不起作用,我没有收到任何错误但没有起作用。我不知道为什么会这样。任何人都知道,请帮助解决此问题。
演示:https://stackblitz.com/edit/angular-8-reactive-form-validation-2kckz4?file=app/app.component.ts
app.component.html:
<form class="tm-edit-product-form" [formGroup]="addProductForm" (ngSubmit)="onSubmit()">
<div class="form-group mb-3">
<label for="category">Category</label>
<select class="custom-select tm-select-accounts" formcontrolname="category" [ngClass]="{ 'is-invalid': submitted && p.category.errors }">
<option value="" disabled selected="true">Select category</option>
<option [value]="i" *ngFor="let i of options">{{ i }}</option>
</select>
<div *ngIf="submitted && p.category.errors" class="invalid-feedback">
<div *ngIf="p.category.errors.required">
Category is required
</div>
</div>
</div>
<div class="form-group mb-3">
<label for="name">Product Name</label>
<input type="text" class="form-control validate" formcontrolname="product_name" [ngClass]="{ 'is-invalid': submitted && p.product_name.errors }" />
<div *ngIf="submitted && p.product_name.errors" class="invalid-feedback">
<div *ngIf="p.product_name.errors.required">
Product name is required
</div>
</div>
</div>
<div class="row">
<div class="form-group mb-3 col-xs-12 col-sm-6">
<label for="name">Product Weight</label>
<input type="text" class="form-control validate" formcontrolname="product_weight" [ngClass]="{'is-invalid': submitted && p.product_weight.errors }" />
<div *ngIf="submitted && p.product_weight.errors" class="invalid-feedback">
<div *ngIf="p.product_weight.errors.required">
Product weight is required
</div>
</div>
</div>
</div>
<div class="col-12">
<div class="options btn-group mt-3">
<button type="submit" class="btn btn-primary rounded ml-3">
Add Product Now
</button>
<button class="btn btn-secondary ml-4 rounded" type="reset" (click)="onReset()">
Reset
</button>
<button type="button" class="btn btn-outline-dark ml-4 rounded" (click)="modal.close('Close click')">
Close
</button>
</div>
</div>
</form>
app.component.ts:
ngOnInit() {
this.addProductForm = this.formBuilder.group({
category: ['', Validators.required],
product_name: ['', Validators.required],
product_weight: ['', Validators.required]
}); }