[英]How to bind data that come from database into angular dynamic form dropdown?
I am creating Angular7 dynamic form and this form contains a dropdown. 我正在创建Angular7动态表单,此表单包含一个下拉列表。 This dropdown has options property. 该下拉菜单具有options属性。 I want to populate this property from the database. 我想从数据库中填充此属性。 But in the official Angular Dynamic Form document, values insert into options property while inputs are being created. 但是在正式的Angular Dynamic Form文档中,值会在创建输入时插入options属性。
I tried this one: 我尝试了这个:
this.formComponent.form.controls['currencyId'].patchValue([{value: '076398a7-ea74-431c-9c63-121af6fe0f2f', label: 'deneme'}]);
new InputDropdown({
key: 'parentJobDepartmentId',
label: '...',
options: [],
value: '...',
required: false,
order: 2
})
I am using ng-select library for dropdown. 我正在使用ng-select库进行下拉。
<ng-select [ngClass]="'ng-select'" [options]="input.options" [formControlName]="input.key" [id]="input.key" (change)="input.onChange($event.target.value)"></ng-select>
I need to populate InputDropdown.options property dynamically(from the database.). 我需要动态填充InputDropdown.options属性(从数据库中)。
How can I do that? 我怎样才能做到这一点? Could you help me with this problem? 您能帮我解决这个问题吗?
If you aren't looking to continuously update these values from the DB then i would suggest building your form up in stages and only assigning the options to the form component once ready. 如果您不希望从数据库中不断更新这些值,那么我建议分阶段构建表单,并在准备好后仅将选项分配给表单组件。
You could use forkJoin
for this. 您可以为此使用forkJoin
。
forkJoin(this.part1(), this.part2()).subscribe(
next: value => {
form_fields = value.flat(1)
}
complete: () => {
// You can sort here as well to keep correct ordering
form_fields.sort((a, b) => a.order - b.order);
this.options = form_fields;
}
)
Then pass `[options]="options" to your component and wrap component in *ngIf="questions" then it will hold until ready. 然后将`[options] =“ options”传递给您的组件,并将组件包装在* ngIf =“ questions”中,它将一直保持到准备就绪为止。
This is probably not the ideal solution but its how i have tackled it in the past. 这可能不是理想的解决方案,但它是我过去如何解决的方法。 Hope it helps. 希望能帮助到你。
Here is how bind data came from database into dropdowns. 这是绑定数据从数据库到下拉列表的方式。
If you call data that you need in ngOnInit
, then you are letting data that captured before UI codes. 如果您在ngOnInit
调用所需的数据,那么您要让捕获的数据在UI代码之前。
ngOnInit(): void {
this.getJobDepartments();
}
When you call UI code in ngAfterViewInit
then you can make sure that first, you get data then the UI. 当您在ngAfterViewInit
调用UI代码时,可以确保首先获取数据,然后获取UI。
ngAfterViewInit(): void {
this.inputs = this.getInputs();
}
And you can use data in dropdown like below. 您可以在下拉菜单中使用数据,如下所示。
new InputDropdown({
key: 'parentJobDepartmentId',
label: '...',
options: this.jobDepartments,
value: '...',
required: false,
order: 2
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.