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

问题描述 投票:0回答:1

我正在使用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中添加了一个示例项目

angular angular7 angular8 angular-reactive-forms ngx-select-dropdown
1个回答
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;
  }
}

希望这会有所帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.