我嘗試對我的輸入字段進行驗證。Angular 2表單驗證,hasError不是函數
這是一段代碼,我用:
DepartmentComponent
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'];
}
DepartmentComponent模板
<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>
的問題是,我得到了一個錯誤:.hasError不是一個功能。 hasError函數在我的html文件中(你可以看到)我真的沒有看到我錯在哪裏。我所做的一切都是在教程中描述的,但無法弄清楚爲什麼會發生這種情況。謝謝你的建議!
儘量'* ngIf =「('需要departmentLocation?.hasError '')'' –
我解決了這個問題:* ngIf =「myForm.controls ['departmentName']。hasError('required')」。我只是不清楚它爲什麼這樣工作:/ –
但這些行'this.departmentName = this.myForm.controls ['departmentName'];'在構造函數內?從代碼中不完全清楚,因爲缺少'}。 –