0

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

4

1 回答 1

0

这是有关如何执行此操作的工作示例。以及代码。同样正如上面评论中所建议的,该组件需要一系列选项。请阅读文档以获取更多详细信息

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;
  }
}

希望这可以帮助 :)

于 2020-03-05T05:06:40.807 回答