如何在Angular 4及更高版本的ngx-select中获取默认选择的值?

时间:2018-06-29 04:02:55

标签: angular typescript select

我正在尝试实现可搜索的选择框,其中数据来自API。我已经显示了用于循环和搜索的数据工作正常。现在,我需要为默认值设置相同的值,而且我正在使用反应式表单。

这是HTML部分:

<ngx-select [formControl]="selectedUserId" 
                      [allowClear]="true"
                      [items]="userData"
                      placeholder="Select User ID"
                      >
        </ngx-select>

这是TS部分:

constructor(private http: HttpService, private fb: FormBuilder, public usr?: UserService, public datepipe?: DatePipe) {
    this.http.getMethod('User/masterpasswordchange').subscribe((data: any) => {
      const items1: Array<any> = [];
      for (let i = 0; i < Object.keys(data).length; i++) {
        items1.push(data[i].userid);
      }
      this.userData = items1;
      this.atAdminName = this.fb.group({
        fromDate: new FormControl(new Date(), Validators.required),
        toDate: new FormControl(new Date(), Validators.required),
        selectedUserId: new FormControl('', Validators.required)
      })
    });
  }

2 个答案:

答案 0 :(得分:1)

formControlName属性添加到选择中。

<ngx-select formControlName="selectedUserId" [allowClear]="true" [items]="userData" placeholder="Select User ID">
</ngx-select>

现在设置默认值。

this.atAdminName .controls['selectedUserId'].setValue('yourValue', {onlySelf: true});

答案 1 :(得分:0)

请注意下面的解决方案

 constructor(private http: HttpService, private fb: FormBuilder, public usr?: UserService, public datepipe?: DatePipe) {
    this.fetchdata();
  }

  formFunction(data) {
    this.atAdminName = this.fb.group({
      fromDate: new FormControl(new Date(), Validators.required),
      toDate: new FormControl(new Date(), Validators.required),
      selectedUserId: new FormControl(data[3], Validators.required)
    });
  }

  fetchdata() {
    this.http.getMethod('User/masterpasswordchange').subscribe((data: any) => {
      const items1: Array<any> = [];
      for (let i = 0; i < Object.keys(data).length; i++) {
        items1.push(data[i].userid);
      }
      this.userData = items1;
      console.log(this.userData);
      this.formFunction(this.userData);
    });
  }