Angular 2 Formularvalidierung, hasError ist keine Funktion
Ich versuche, eine Validierung für meine Eingabefelder zu erstellen.
Dies ist ein Stück Code, das ich verwendet habe:
AbteilungsKomponente
import {
FORM_DIRECTIVES,
FormBuilder,
ControlGroup,
Validators ,
AbstractControl
} from 'angular2/common';
@Component({
selector: 'my-departments',
providers: [HTTP_PROVIDERS, DepartmentService],
directives: [FORM_DIRECTIVES, Alert],
styleUrls: ['app/department.component.css'],
templateUrl: 'app/department.component.html',
pipes:[SearchPipe]
})
export class DepartmentComponent implements OnInit {
myForm: ControlGroup;
departmentName: AbstractControl;
departmentLocation: AbstractControl;
constructor(private _router: Router, private _departmentService: DepartmentService, fb: FormBuilder) {
this.myForm = fb.group({
'departmentName': ['', Validators.required],
'departmentLocation': ['', Validators.required]
});
this.departmentName= this.myForm.controls['departmentName'];
this.departmentLocation= this.myForm.controls['departmentLocation'];
}
AbteilungsComponent-Vorlage
<form [ngFormModel]="myForm"
(ngSubmit)="addDepartment(newItem)" [hidden]="!showAddView" align="center">
<div>
<label for="editAbrv">Department name:</label><br>
<input type="text" [(ngModel)]="newItem.departmentName" [ngFormControl]="myForm.controls['departmentName']" >
<div *ngIf="departmentName.hasError('required')" class="ui error message"><b style="color:red;">Name is required</b></div>
</div>
<div>
<label for="editAbrv">Department Location:</label><br>
<input type="text" [(ngModel)]="newItem.departmentLocation" [ngFormControl]="myForm.controls['departmentLocation']" >
<div *ngIf="departmentLocation.hasError('required')" class="ui error message"><b style="color:red;">Location is required</b></div>
</div>
<div>
<button type="submit" class="ui button">Submit</button>
<button><a href="javascript:void(0);" (click)="showHide($event)" >
Cancel
</a></button>
</div>
</form>
Das Problem ist, dass ich einen Fehler bekommen habe: .hasError ist keine Funktion. Die hasError-Funktion ist in meiner HTML-Datei (die Sie sehen können). Ich sehe wirklich nicht, wo mein Fehler liegt. Ich habe alles so gemacht, wie im Tutorial beschrieben, kann aber nicht herausfinden, warum dies passiert. Danke für den Rat!
Antwort #1
du solltest *ngIf="myForm.controls['departmentLocation'].hasError('required')" verwenden
oder besseres Glück mit this.departmentName= this.myForm.controls.find('departmentName'); ?
Antwort #2
Anstelle von hasError sollten Sie errors verwenden
d.h. es sollte sein
myForm.controls['departmentLocation'].errors['required']
d.h. mit *ngIf
*ngIf="myForm.controls['departmentLocation'].errors['required']"
