I am validating my HTML form in Angular 4 , wanted to enable/disable a button by checking if a form is valid/invalid
<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>
component file :
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
}
}
Even though when both the input fields are empty and showing the validation error shiftForm.invalid is still not disabling the button. I have tried shiftForm.form.shiftName.invalid, shiftform.shiftName.invalid, shiftForm.form['shiftName'].invalid,shiftForm.controls['shiftName'].invalid etc.. None of them are working. Even when i try just the element name directly like shiftName.invalid or shiftName.errors still the button is not getting disabled.
What am i doing wrong ? I wanted to validate the form in HTML file only, do not want to do reactive form validation in the typescript file.