我正在尝试验证我的表单但是未定义的错误被触及,认为我对导入文件做错了,可以请一些人给我一些帮助。
我的模板,
<h3 class = "head">MY PROFILE</h3>
<form [formGroup]="form" (ngSubmit)="onSubmit(form.value)">
<div class="row">
<div class="form-group">
<label class="formHeading">firstname</label>
<input type="text" id="facebook" class="form-control" [formControl]="form.controls['firstname']" >
</div>
<div *ngIf ="firstname.touched">
<div *ngIf ="!firstname.valid" class = "alert alert-danger">
<strong>First name is required</strong>
</div>
</div>
</div>
</form>
我的组件,
import {Component} from '@angular/core';
import {Http, Response, Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Subject } from 'rxjs/Subject';
import {CORE_DIRECTIVES} from '@angular/common';
import { Router, ROUTER_DIRECTIVES } from '@angular/router';
import {Control,ControlGroup} from '@angular/common';
import {FORM_DIRECTIVES,FormBuilder,FormGroup,Validators, REACTIVE_FORM_DIRECTIVES} from '@angular/forms';
Component({
templateUrl: './components/profile/profile.html',
directives: [CORE_DIRECTIVES,ROUTER_DIRECTIVES,FORM_DIRECTIVES,REACTIVE_FORM_DIRECTIVES],
})
export class Profile {
http: Http;
form: FormGroup;
constructor(fbld: FormBuilder,http: Http,public router: Router) {
this.http = http;
this.form = fbld .group({
firstname: ['', Validators.required],
lastname: ['', Validators.required],
profilename :['', Validators.required],
image : [''],
phone : ['']
});
}
onSubmit(form) {
console.log(form);
var headers = new Headers();
headers.append('Content-Type','application/x-www-form-urlencoded');
this.http.post('http://localhost/angular/index.php/profile/addprofile', JSON.stringify(form),{headers:headers});
subscribe(response => {
if(response.json().error_code === 0) {
alert('added successfully');
this.router.navigate(['/demo/professional']);
} else {
alert('fail');
}
});
}
}
我正在尝试验证我的表单,但触摸错误未定义,认为我对导入文件做错了。有人可以请我帮忙。
答案 0 :(得分:0)
您必须在表单中找到控件。尝试使用:
form.controls['firstname'].touched
和
form.controls['firstname'].valid