如何将角度FormArray绑定到ngx-select-dropdown

时间:2019-06-17 13:53:33

标签: angular angular7 angular-reactive-forms ngx-bootstrap angular8

我正在使用 ReactiveForms 编写angular7单页Web应用程序。 我需要在可搜索的下拉列表中列出客户的集合,为此,我尝试使用ngx-select-dropdownhttps://www.npmjs.com/package/ngx-select-dropdown

我的客户类别如下所示

export class Customer{
  public id:number;
  public name:string;

  constructor(cusId:number, cusName:string){
    this.id = cusId;
    this.name = cusName;
  }
}

我的组件类如下

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormArray } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  public myForm: FormGroup;
  constructor(private formBuilder: FormBuilder) {
  }
  ngOnInit() {
    this.myForm = this.formBuilder.group({
      selectedCustomer: [],
      customers: this.formBuilder.array([
        new Customer(0, "Andrew"),
        new Customer(1, "Steve"),
        new Customer(2, "Frank"),
        new Customer(3, "Jimmie")
      ])
    })
  }
}

我的HTML模板如下

<div [formGroup]="myForm">
  <ngx-select-dropdown formControlName="customers"></ngx-select-dropdown>
</div>

我想要的是具有以下选项的客户下拉列表。

  1. 下拉列表应该可以搜索。
  2. 下拉列表应为单选。
  3. 选择项目时,应更新“ selectedCustomer”表单控件。 (请参见此演示中的“单选下拉列表”示例:https://manishjanky.github.io/ngx-select-dropdown/

我在stackblitz中添加了一个示例项目

1 个答案:

答案 0 :(得分:0)

这是如何执行此操作的working sample。还有代码。同样,如上面的注释中所建议,组件需要一组选项。请阅读documentation了解更多详情

HTML

<div [formGroup]="myForm">
  <ngx-select-dropdown  [config]="config" [options]="custOptions" formControlName="customers"></ngx-select-dropdown>
</div>

TS

import { Component, OnInit } from "@angular/core";
import { FormGroup, FormBuilder, FormArray } from "@angular/forms";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  public myForm: FormGroup;
  config={
    search:true,
    displayKey:'name'
  }
  custOptions = [
        new Customer(0, "Andrew"),
        new Customer(1, "Steve"),
        new Customer(2, "Frank"),
        new Customer(3, "Jimmie")
      ];
  constructor(private formBuilder: FormBuilder) {}
  ngOnInit() {
    this.myForm = this.formBuilder.group({
      selectedCustomer: [],
      customers: [""]
    });
  }
}

export class Customer {
  public id: number;
  public name: string;

  constructor(cusId: number, cusName: string) {
    this.id = cusId;
    this.name = cusName;
  }
}

希望这会有所帮助:)