多选不起作用,并给出错误'this.validator不是函数' - Angular2

时间:2017-02-28 14:24:33

标签: javascript angular

当我尝试设置多重选择值时,它会给我一个错误,如

  

this.validator不是函数

在Angular2 FormBuilder中。

这是我的代码:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Http, Headers } from '@angular/http';
import { Router,ActivatedRoute } from '@angular/router';
import 'rxjs/add/operator/map';

@Component({
   selector: 'app-user',
   templateUrl: './user.component.html',
   styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {

userID: number;
public headers;
public user;

constructor(public fb: FormBuilder, public _router: Router, public http: Http, private route: ActivatedRoute) {
   this.user = this.fb.group({
      name: ["", Validators.required],
      age: ["", Validators.required],
      gender: ["", Validators.required],
      role: ["", Validators.required],
      theme: ["", Validators.required],
      isActive: ["", Validators.required],
      topics: ["", Validators.required],
      toggle: ["", Validators.required],
      address: ["", Validators.required],
   });
}

doLogin(event) {
   console.log(event);
}

public genders = [
   { value: 'F', display: 'Female' },
   { value: 'M', display: 'Male' }
];

public roles = [
   { value: 'admin', display: 'Administrator' },
   { value: 'guest', display: 'Guest' },
   { value: 'custom', display: 'Custom' }
]
public themes = [
   { backgroundColor: 'black', fontColor: 'white', display: 'Dark' },
   { backgroundColor: 'white', fontColor: 'black', display: 'Light' },
   { backgroundColor: 'grey', fontColor: 'white', display: 'Sleek' }
];

public topics = [
   { value: 'game', display: 'Gaming' },
   { value: 'tech', display: 'Technology' },
   { value: 'life', display: 'Lifestyle' },
];

public toggles = [
   { value: 'toggled', display: 'Toggled' },
   { value: 'untoggled', display: 'UnToggled' },
];

public t = {
   true: { value: 'toggled', display: 'Toggled' },
   false: { value: 'untoggled', display: 'UnToggled' }
}




ngOnInit() {

   this.user =   this.fb.group({
      "id":"8",
      "name":"df",
      "gender":"M", 
      "role":"guest",
      "theme":{ 
          backgroundColor: 'black', 
          fontColor: 'white', 
          display: 'Dark' 
      },
      "isActive":"0",
      "toggle":"toggled",
      "topics":[ "tech", "life" ],
      "age":'500',
      "address":"sdf"
    });

}
}

最后,我需要在主题字段中设置一个格式值数组。当我没有设置静态值并通过表单选择选项,并打印此表单值时,它的(主题字段)已经打印了一个数组格式值:

enter image description here

1 个答案:

答案 0 :(得分:2)

在构造函数中替换

topics: ["", Validators.required],

topics: [[""], Validators.required],

并在ngOnInit方法中更改

this.user =   this.fb.group

this.user.setValue

我面临同样的问题以及随后为我工作的变化

仅供参考,如果您需要设置单个值,则需要使用this.user.patchValue({fieldName:'fieldValue'})