Angular 2打字稿:TypeError:this.validator不是一个函数 [英] Angular 2 Typescript: TypeError: this.validator is not a function
问题描述
我正在使用ControlGroup构建表单,并在其中加载类对象.但是,我一半时间遇到标题中提到的错误.有些表格可以载入,有些则不会.
I'm building a form with ControlGroup and I'm loading a class object in it. However I'm running into the error mentioned in the title half of the time. Some forms do load and some don't.
我有一个类似的类文件:
I have a class file like so:
export class User {
id: number;
email: string;
sign_in_count: number;
created_at: string;
first_name: string;
last_name: string;
birth_date: Date;
news_letter: boolean;
fb_id: string;
gender: boolean;
phone: string;
picture: any;
}
在我的UserDetailComponent中,我将类加载到控件中,如下所示:
In my UserDetailComponent I load the class in the control like this:
export class UserDetailComponent implements OnInit {
user: User;
userDetailForm: ControlGroup;
constructor(
private form: FormBuilder,
private _userService: UserService,
private _router: Router,
private params: RouteSegment
) { }
ngOnInit() {
this.user = this._userService.getUser();
if (this.user === undefined) {
this._userService.getSingleUser(this.params.getParam('id'))
.subscribe(data => (this.user = data, this.setForm()));
} else {
this.setForm();
}
}
setForm() {
this.userDetailForm = this.form.group(this.user);
}
}
在最后一行,我得到了堆栈跟踪如下的错误:
On that last line I get the error of which the stacktrace is below:
browser_adapter.ts:78 TypeError: this.validator is not a function
at Control.AbstractControl._runValidator (model.ts:146)
at Control.AbstractControl.updateValueAndValidity (model.ts:128)
at new Control (model.ts:282)
at FormBuilder.control (form_builder.ts:32)
at FormBuilder._createControl (form_builder.ts:66)
at eval (form_builder.ts:50)
at Function.StringMapWrapper.forEach (collection.ts:132)
at FormBuilder._reduceControls (form_builder.ts:49)
at FormBuilder.group (form_builder.ts:19)
at UserDetailComponent.setForm (user-detail.component.ts:95)
推荐答案
当我以错误的方式绑定表单构建器中的值数组时,出现了此错误.
I had this error when I was binding an array of values in form builder the wrong way.
我做什么:
fb.group({items: [1, 2, 3, 4]})
应如何设置:
fb.group({items: [[1, 2, 3, 4]]})
您必须将所有内容包装到一个数组中,否则angular会认为[1, 2, 3, 4]
是 form控件定义,而不是 form控件值.
You have to wrap everything into an array, otherwise angular thinks that [1, 2, 3, 4]
is a form control definition rather then a form control value.
这篇关于Angular 2打字稿:TypeError:this.validator不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!