【发布时间】:2018-09-04 03:10:35
【问题描述】:
我正在 Angular 4 中验证我的 HTML 表单,想通过检查表单是否有效/无效来启用/禁用按钮
<form novalidate #shiftForm="ngForm">
<table>
<thead>
<th>Name</th>
<th>time</th>
</thead>
<tbody *ngFor=let item of Items>
<tr>
<td>
<div class="form-group">
<input class="form-control" type="text" required name="shiftName"
[(ngModel)]="item.ShiftName"#shiftName="ngModel" id="shiftName">
<div *ngIf="shiftName.invalid && (shiftName.dirty || shiftName.touched)" class="alert alert-danger">
<div *ngIf="shiftName.errors.required">REQUIRED</div>
</div>
</div>
</td>
<td>
<div class="form-group">
<input class="form-control" type="text" required name="shiftTime"
[(ngModel)]="item.ShiftTime" #shiftTime="ngModel" id="shiftTime">
<div *ngIf="ShiftTime.invalid && (ShiftTime.dirty || ShiftTime.touched)" class="alert alert-danger">
<div *ngIf="ShiftTime.errors.required">REQUIRED</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
<button [disabled]="shiftForm.invalid"
(click)="updateItems()">APPLY
</button>
</form>
组件文件:
import {Component, OnInit, Inject, ViewChild, SimpleChange, SimpleChanges} from '@angular/core';
import {ElementRef, Renderer2} from '@angular/core';
import {Transition, StateService} from '@uirouter/angular';
import {ViewEncapsulation} from '@angular/core';
@Component({
selector: 'shift-details',
templateUrl: './shift-details.component.html',
styleUrls: ['./shift-details.component.less'],
encapsulation: ViewEncapsulation.None
})
export class ShiftDetailsComponent implements OnInit {
//variable declaration
Items:any = [];
constructor(
private rd: Renderer2,
private transition: Transition,
private $state: StateService) {
this.$stateParams = transition.params();
}
ngOnInit() {
this.Items = getShiftItems();
}
getShiftItems() {
//calling the service here to load the data in this.Items
}
updateItems() {
//calling the service here to update this.Items
}
}
即使两个输入字段都为空并显示验证错误shiftForm.invalid 仍然没有禁用按钮。我试过shiftForm.form.shiftName.invalid、shiftform.shiftName.invalid、shiftForm.form['shiftName'].invalid、shiftForm.controls['shiftName'].invalid 等。它们都没有工作。即使我直接尝试像shiftName.invalid 或shiftName.errors 这样的元素名称,按钮仍然没有被禁用。
我做错了什么?我只想验证 HTML 文件中的表单,不想在 typescript 文件中进行响应式表单验证。
【问题讨论】:
-
你能添加你的component.ts文件吗
标签: html angular angular4-forms