2017-02-28 45 views
1

當我嘗試設置多選值,它給了我像多選擇不工作,並給出錯誤「this.validator不是一個函數」 - Angular2

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

+0

格式化爲清楚起見 – Soraz

回答

1

在構造函數替換

topics: ["", Validators.required], 

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

和ngOnInit方法變更

工作

this.user = this.fb.group 

this.user.setValue 

我都面臨着同樣的問題,以下更改僅供參考,如果您需要設置一個值,那麼你需要使用this.user.patchValue({fieldName:'fieldValue'})

相關問題