Assigning a Value to a Dropdown Menu in Angular

I have some JSON data that contains a True/False value. Depending on whether it is true or false, I want a specific option in a Select Dropdown to be automatically selected.

This is the HTML code using Angular 16:

<select name="reportNo" id="reportNo" class="form-select" [(ngModel)]="reportInfo.active">
      <option value="true"> Activated </option>
      <option value="false"> Deactivated </option>
</select>  

Here is an example of the JSON data:

"reportInfo": {
   "active": true,
}

If the "active" value is true, then the option for "Activated" should be selected. Otherwise, if it is false, the "Deactivated" option should be selected.

Answer №1

Here is an example of code that works perfectly!

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import 'zone.js';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [FormsModule],
  template: `
    <select name="reportNo" id="reportNo" class="bea-form-select" [(ngModel)]="reportInfo.active">
      <option value="true"> Activated </option>
      <option value="false"> Deactivated </option>
</select>  
{{reportInfo.active}}
  `,
})
export class App {
  reportInfo = {
    active: true,
  };
}

bootstrapApplication(App);

Check out the demo on StackBlitz

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

An assortment of the most similar values from a pair of arrays

I am seeking an algorithm optimization for solving a specific problem that may be challenging to explain. My focus is not on speed or performance, but rather on simplicity and readability of the code. I wonder if someone has a more elegant solution than mi ...

javascript: window.open()

I am currently using VB.NET 2005 and I have a requirement to launch a new browser window using Process.Start(). The challenge is that I need to specify the size of the browser window, for example, height:300 and width:500. Process.Start("firefox.exe", "ab ...

Exploring nested routes with HashRouter in React

I've been working on a dashboard/admin control panel application using React, but I'm facing some challenges when it comes to handling component rendering accurately. Initially, my main App component is structured like this: <React.Fragment&g ...

Error: The function User.findOne is not recognized

Currently, I am in the process of developing a Node.js API and aiming to implement JWT for login functionality. I have successfully set up the model and route, and while testing with Postman using the POST method, an error occurs upon sending the request. ...

shared interfaces in a complete javascript application

In the past, I have typically used different languages for front-end and back-end development. But now, I want to explore the benefits of using JavaScript/TypeScript on both sides so that I can have key data models defined in one central location for both ...

cycle through several handlebars entities

Hey friends, I could really use your help right now. I'm attempting to iterate through these objects using handlebars. RowDataPacket { idUser: 1, username: 'xxxxxx', password: 'xxxxx', fullname: 'Julian Rincon'}, RowDat ...

"Learn the steps to access a JSON file directly from a URL within a Next.js

My goal is to upload a JSON file to the server from a URL, open it, parse it, and display its features on Google Maps. However, I am encountering an error with the "fs" library preventing me from opening the file. Below is the code: "use client" ...

I am experiencing an issue where localhost is not displaying the JSON output for the Router and controller that I have

Recently delving into the world of NodeJS, I find myself facing a roadblock. While attempting to manage requests, my localhost appears to be endlessly loading or throwing an error. Error: cannot GET/ I aim to showcase the JSON data on my local site. Wh ...

Error TS2322: Type 'boolean' cannot be assigned to type 'undefined'. What is the best approach for dynamically assigning optional properties?

I am currently working on defining an interface named ParsedArguments to assign properties to an object, and here is what it looks like: import {Rules} from "../Rules/types/Rules"; export interface ParsedArguments { //other props //... ...

Function that returns an Observable<Boolean> value is null following a catch block

Why is the login status null instead of false in this method? // In the method below, I am trying to return only true or false. isLoggedIn(): Observable<boolean> { return this .loadToken() .catch(e => { this.logger ...

How to display text on a new line using HTML and CSS?

How can I properly display formatted text in HTML with a text string from my database? The text should be contained within a <div class="col-xs-12"> and nested inside the div, there should be a <pre> tag. When the text size exceeds the width o ...

Occasionally, data may fail to be fetched when using a Jquery GET

Here's what I've narrowed it down to: $.getJSON('/drinks/getColors', function(items) { colors = items; }); $.each(colors, function(index2, value2) { if (value.name == value2.name) { curColor = value2.color; } }); ...

Creating connections between different services and components

I'm having an issue with importing my service into my component as it's giving me a "cannot find module" error. Below is the code from selectHotel.component.ts import { Component } from '@angular/core'; import { GetHotelService } from ...

Issue: Debug Failure. Invalid expression: import= for internal module references should have been addressed in a previous transformer

While working on my Nest build script, I encountered the following error message: Error Debug Failure. False expression: import= for internal module references should be handled in an earlier transformer. I am having trouble comprehending what this erro ...

What is the best way to display long text in a browser alert without it being cut off?

Seeking to display a large amount of data in an alert box, but only a portion is currently visible. The following text is all that can be seen: ["19467,1496257152583","19227,1496256651094","19469,1496257033968","17285, ...

Steps for removing an element from an array using Mongoose and Node.js

After reading and attempting to implement the solutions provided by others, I am still struggling to understand why it's not working for me. This is my first project involving backend development. While progressing through a course, I decided to work ...

Using Node.js for a game loop provides a more accurate alternative to setInterval

In my current setup, I have a multiplayer game that utilizes sockets for asynchronous data transfer. The game features a game loop that should tick every 500ms to handle player updates such as position and appearance. var self = this; this.gameLoop = se ...

Setting up the Angular 2 router to function from the /src subfolder

My goal is to create two separate subfolders within my project: src and dist. Here are the key elements of my application: root folder: C:\Server\htdocs\ app folder: C:\Server\htdocs\src index.html contains <base href="/ ...

Using Typescript for Asynchronous Https Requests

I've been attempting all day to make an https request work. My current code isn't functioning as expected; when I run it, I encounter an "Unhandled error RangeError: Maximum call stack size exceeded at Function.entries" import * as https from &q ...

What is the best method for implementing click functionality to elements that share a common class using only pure JavaScript

I am struggling to figure out how to select specific elements with the same classes using only pure JavaScript (no jQuery). For example: <div class="item"> <div class="divInside"></div> </div> <div class= ...