我正在使用 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中添加了一个示例项目
答案 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;
}
}
希望这会有所帮助:)