简体   繁体   中英

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. This dropdown has options property. 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.

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 [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.).

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(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.

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(): void {
    this.getJobDepartments();
  }

When you call UI code in ngAfterViewInit then you can make sure that first, you get data then the 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
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM