Home > Back-end >  How to display db value in the dropdown as default value
How to display db value in the dropdown as default value

Time:05-11

i need your help, i got a project with a lot to do and to be honest i can't finish it without help. As i'm new in Angular & Springboot with small basic knowledge i'm not able to continue the project they gave me.

One of the issue i have is some dropdown list does not display the selected value coming from the DB, it's a custom component.

[select.component.html]

<ng-container *ngIf="config">
  <label>{{config.label.label | translate:config.label.params}}</label>
  <select  [formControl]="config.ctrl" (blur)="onBlur.emit()">
    <option>{{'common.select.default' | translate}}</option>
    <option *ngFor="let option of config.values" value="{{option.value}}">{{option.label | translate}}</option>
  </select>
</ng-container>

[select.component.ts]

import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {SelectConfig} from '@shared/model/select.config';

@Component({
  selector: 'app-select',
  templateUrl: './select.component.html',
  styleUrls: ['./select.component.scss']
})
export class SelectComponent implements OnInit {
  @Input() config!: SelectConfig;
  @Output() onBlur = new EventEmitter<void>();

  constructor() {
  }

  ngOnInit(): void {
  }

  ngOnChange() {

  }
}

[select.config.ts]

import { LabelWithParam } from '@shared/model/label-with-params';
import { FormControl } from '@angular/forms';


export interface SelectConfig {
  values: SelectOption[];
  label: LabelWithParam;
  placeholder: string;
  ctrl: FormControl;
}

export interface SelectOption {
  value: any;
  label: string;
}

[detail.html]

  <app-select *ngIf="actifSelectConfig$ | async as actifSelectConfig"
              [config]="actifSelectConfig"
              (onBlur)="update()">
  </app-select>

[detail.ts]

  public getControl(name: string): FormControl {
    return this.formGroup.get(name) as FormControl;
  }

this.actifSelectConfig$.next( {
  label: {label: 'form.user.label.active'},
  placeholder: 'form.user.placeholder.active',
  ctrl: this.getControl('active'),
  values: ActifHelper.toSelectOption()
});

i don't know how to display the DB value in the dropdown, instead it stay on the option "Select a value".

Thks!

CodePudding user response:

Use [ngValue]:

<option *ngFor="let option of config.values" [ngValue]="option">{{option.label | translate}}</option>

I assume you set the selected value with this.getControl('active'):

getControl(): FormControl {
    return this.formBuilder.control(VALUE_FROM_THE_DB);
}

CodePudding user response:

Problem solved, the working line is:

<option *ngFor="let option of config.values" ngValue="{{option.value}}">{{option.label | translate}}</option>

i put ngValue="{{option.value}} instead of value="{{option.value}} and the issue is solved, got the value from the db now

  • Related