Steps to automatically set the database value as the default option in a dropdown menu

I'm in need of assistance with a project that I'm working on. To be completely honest, I am struggling to complete it without some help. Since I am new to Angular and Springboot with only basic knowledge, I have hit a roadblock and can't make progress on the project assigned to me.

One of the main issues I am facing is that some dropdown lists are not showing the selected values retrieved from the database. It seems to be a problem with a custom component.

[select.component.html]

<ng-container *ngIf="config">
  <label>{{config.label.label | translate:config.label.params}}</label>
  <select class="form-control form-control-sm" [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 am currently struggling to figure out how to display the DB value in the dropdown list, as it remains stuck on the default option "Select a value."

Thank you for your help!

Answer №1

Utilize [ngValue] when creating options dynamically:

<option *ngFor="let item of this.items" [ngValue]="item">{{item.name | translate}}</option>

To set the active control value, try implementing it in this.getControl('active') method:

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

Answer №2

After some troubleshooting, I found the solution by modifying the following line:

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

By changing ngValue="{{option.value}} to value="{{option.value}}, I was able to successfully retrieve the value from the database.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The element 'fontFamily' is not recognized within the 'ThemeOptions' type in MUI theming

I'm diving into the world of React and MUI by building my own dashboard from scratch. Let's take a look at my App.tsx file: import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; i ...

Make Ionic 2 Navbar exclusively utilize setRoot() instead of pop()

When navigating to a different page, the ion-navbar component automatically includes a back button that uses the pop() method to return to the previous page. Is there a way to modify this behavior so that it utilizes the setRoot() method instead of pop(), ...

How can you incorporate a module for typings without including it in the final webpack bundle?

As I venture into the realm of Webpack, I am faced with the challenge of transitioning from TypeScript 1.x to TypeScript 2. In my previous projects, I typically worked with TypeScript in one module using separate files, TSD for typings, and compiling throu ...

Best practices for implementing dual ngFor directives within a single tr element?

Click here to view the page The image attached shows the view I want to iterate through two ngFor loops inside the tr tag. When using a div tag inside the tr, it's looping the button next to the tag instead of where I want it in the file table header ...

Is there a way to resolve the issue of retrieving the processed value directly in NestJS's @OnEvent function?

Due to excessive logic in the API and its slow performance, I have resorted to handling some of the logic with @OnEvent. The problem arises when the frontend runs the @GET API immediately after this API, potentially without waiting for @OnEvent to update. ...

Adjust the height of Ngx Editor to meet your specific preferences

I have integrated ngx-editor into my MEAN stack application to create a wysiwyg editor. Everything is functioning as expected, but I am facing an issue with setting the height for the editor. I attempted to define the height in the component's css fil ...

When a reaction function is triggered within a context, it will output four logs to the console and

My pokemon API application is encountering some issues. Firstly, when I attempt to fetch a pokemon, it continuously adds an infinite number of the same pokemon with just one request. Secondly, if I try to input something again, the application freezes enti ...

Getting a specific array from the API with fetch in Angular: A step-by-step guide

I am trying to retrieve images from an API, but I'm having trouble accessing all the arrays to get to the data. Currently, I am only able to fetch the posts arrays in a single call and not beyond that. https://i.stack.imgur.com/aFWlD.jpg My method fo ...

What is the simplest method for converting a large JSON array of objects into an object containing the same data under the key "data" in TypeScript?

What is the most efficient method for converting a large JSON array of objects into an object with a key named "data" using TypeScript: Original Format: [ { "label":"testing", "id":1, "children":[ { "label":"Pream ...

When launching the Angular SSR app, an uncaught ReferenceError occurs because the document is not defined

After successfully running "npm run dev:ssr" a problem arises when the rendered file shows an error. How can this issue be resolved? ERROR Error: Uncaught (in promise): ReferenceError: document is not defined ReferenceError: document is not defined a ...

The express application's GET route is causing a "Cannot GET" error to be thrown

I am managing different types of pages: the main root page (/) today's chapter page (/929 OR /929/) which eventually redirects to /929/<CHAPTER> where <CHAPTER> is a natural number between 1 to 929 individual chapter pages (/929/<CHAP ...

NPM: There are no valid TypeScript file rules specified

Currently working on a small project using React.JS. Whenever I execute : npm run start, the following message gets logged: Starting type checking and linting service... Using 1 worker with 2048MB memory limit Watching: /Users/John/Projects/myProject/src ...

Exploring the functionality of window.matchmedia in React while incorporating Typescript

Recently, I have been working on implementing a dark mode toggle switch in React Typescript. In the past, I successfully built one using plain JavaScript along with useState and window.matchmedia('(prefers-color-scheme dark)').matches. However, w ...

How can I manually listen to Angular 2 events on a dependency injected instance?

Assume I am working with a component: @Component({selector: 'todo-cmp'}) class TodoCmp { @Input() model; @Output() complete = new EventEmitter(); // TypeScript supports initializing fields onCompletedButton() { this.complete.next(); / ...

angular triggering keyup event multiple times

Currently, I am working on a datalist feature. Whenever the user types something into the input field and releases a key, a GET request is made to retrieve an array of strings which are then displayed in the datalist. <input type="text (keyup)=&quo ...

Angular: How to Resolve Validation Error Messages

I have a TypeScript code block: dataxForm: fromGroup this.dataxForm = new FormGroup({ 'Description':new FormControl(null, Validaros.required}; 'Name':new FormControl(null, Validators.required}) Here is an HTML snippet: <mat-divider& ...

In React, the state's value will revert back to its initialState whenever a new value is assigned

My App component has a simple functionality where it controls the state of a value to display a header. By using an onClick function, I'm updating the isHeaderVisible value to True in the Home component when a logo is clicked and another route is take ...

Problem with TypeScript involving parameter destructuring and null coalescing

When using parameter destructuring with null coalescing in TypeScript, there seems to be an issue with the optional name attribute. I prefer not to modify the original code like this: const name = data?.resource?.name ?? [] just to appease TypeScript. How ...

The promise briefly returns a placeholder object before resolving with the actual response

Currently, I am working on a simple check to determine whether myAnswer contains an answer. The checking functionality is operating smoothly; however, the issue arises in the final function that aims to return the string obtained from myAnswer. Instead of ...

How to attach an event listener to an input element using Angular

I am looking to add a listener to an input element that will be triggered every time the user changes the input values. The goal is to display the current values chosen by the user. Example HTML template: <div id="idDoseLabel1" class="da ...