当我注意到,当我没有尝试将任何数据提交到html输入时,我正在尝试构建自定义反应式表单控件验证器函数。 我想知道为什么在检查chrome控制台中的代码时我会将log 2打印三次。
@Component({
selector: 'fourth-app',
templateUrl: './app/Fourth_Component/fourthcomponent.html'
})
@Injectable()
export class FourthComponent implements OnInit {
profileForm: FormGroup;
private ProductName: FormControl;
private Price: FormControl;
private InStock: FormControl;
private ProductCompany: FormControl;
constructor(private http: Http) { }
ngOnInit() {
console.log("1");
this.ProductName = new FormControl('', [Validators.required, Validators.minLength(2)]);
this.Price = new FormControl('',Validators.required);
this.InStock = new FormControl('', [Validators.required, this.inStock]);
this.ProductCompany = new FormControl('', [Validators.required, Validators.minLength(5)]);
this.profileForm = new FormGroup({
ProductName: this.ProductName,
Price: this.Price,
InStock: this.InStock,
ProductCompany: this.ProductCompany
});
}
inStock(control: FormControl) {
console.log("2");
return control.value == "true" ? null : { valid: false };
}
addProduct(formValues: any): void {
if (this.profileForm.valid) {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post('api/Combiners', JSON.stringify(formValues), options)
.map((res: Response) => res.json())
.subscribe(
data => console.log(data),
err => console.log(err),
() => console.log('yay post')
);
}
else {
console.log("User input was invalid!");
}
}
}