我正在使用ReactiveForms编写angular7单页Web应用程序。我需要在可搜索的下拉列表中列出客户的集合,为此,我正在尝试使用ngx-select-dropdown
(https://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>
我想要的是具有以下选项的客户下拉列表。
我已经在stackblitz中添加了一个示例项目
这里是如何执行此操作的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;
}
}
希望这会有所帮助:)