What is the best way to implement a selected option in AngularJS 2?

Trying to understand how to preselect an option when displayed, I attempted it with old JavaScript style code or another language. For example:

<select>
for (x = 0; x < elements.size; x++) {
<option value="element.id" if (element.id == selected.id ) print selected (endif)>element.name</option>
}
</select>

After attempting this in AngularJS, my code ended up looking like the following.

Here is the modified code snippet:

import { Component } from '@angular/core';

export class Category {
    id: number;
    name: String;
    parent_id: number;
}

const CATEGORIES: Category[] = [
    {id: 1, name: "Pants", parent_id: 0},
    {id: 2, name: "Jeans", parent_id: 1},
    // more categories here...
];

@Component({
  template: `
  This is the category page.
  Search:&nbsp;<input type="text" name="search" />
  <button >Search</button>

  <table class="table table-bordered table-hover">
    <tr>
    <th>Id</th>
    <th>Name</th>
    <th>Parent Category</th>
    </tr>
    <tr *ngFor="let cat of categories" (click)="onSelect(cat)">
        <td>{{cat.id}}</td>
        <td><input type="text" value="{{cat.name}}" /></td>
        <td>
            <select>
            <option value="0">&nbsp;</option>
                <option *ngFor="let parent of categories" 
                value="{{parent.id}}">
                    {{parent.name}}
                </option>
            </select>
        </td>
    </tr>
    </table>

  `
})

export class CategoryComponent  { 
    categories = CATEGORIES;

    parents : Category[];

    selectedCategory: Category;

    onSelect(cat: Category): void {
        this.selectedCategory = cat;
    }

    parentCategories() : Category[] {
        var parents : Category[];
        for (let cat of this.categories ) {
            if (cat.parent_id == 0 ) {
                parents.push(cat);
            }
        }
        return parents;
    }
}

How can I properly accomplish this task?

Answer №1

Why not include [(ngModel)]="selectedValue" in your select? According to the guidance provided in the official Angular documentation:

<select class="form-control"  id="power"
      required
      [(ngModel)]="model.power" name="power">
  <option *ngFor="let pow of powers" [value]="pow">{{pow}}</option>
</select>

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

Ignore unused variables in typescript with eslint disable

When working on a Typescript React project, I often use placeholder variables in the code to lay everything out before implementation. However, this results in numerous eslint no-unused-vars errors, making it difficult to spot real errors. Is there a way ...

Steps for displaying a 404 page on a server-side rendered dynamic route following a client-side page transition

I'm currently developing a next.js project using Contentful as the Content Management System. My goal is to display a 404 page for a server-side rendered dynamic route after a client-side page transition. When I directly request the page (by entering ...

User Interface showcasing real-time progress data pulled from API

Currently, I am facing a situation where there are three docker containers involved in my project: - An angular frontend - A Django backend - A Python processing API The scenario is such that a user uploads a file to the backend volume through the fronten ...

Commitment and follow through

I am encountering an issue in my Angular2 (ionic2) application. There seems to be a problem with the "subscribe" property not existing on this.cityService.getAllCities(). Within cityPage.ts, there is a function structured like this: getCities(){ this ...

A guide to verifying the type of response from an HTTP request in Typescript

Issue: I am currently working with Firebase cloud functions and encountering a specific problem. Let's consider the following function: function giveMeAnInteger(): number { return 123; } When calling this function like so: function call() { ...

Generate gzipped files using Angular CLI

I am attempting to populate a dist folder with the standard files along with their .gz versions. To achieve this, I used ng eject to obtain the webpack.config.js file in order to integrate the compression plugin from https://github.com/webpack-contrib/comp ...

Creating a personalized connect function in Typescript for react-redux applications

Currently, I am in the process of migrating a large and intricate application to Typescript. One specific challenge we are facing is our reliance on createProvider and the storeKey option for linking our containers to the store. With over 100 containers in ...

The primary origin of TypeScript is derived from the compiled JavaScript and its corresponding source map

Being new to sourcemaps and typescript, I am faced with a project that has been compiled into a single javascript file from multiple typescript files. The files available to me are: lib.js (the compiled js code of the project) lib.js.map (the source map ...

Tips for achieving asynchronous data retrieval using Angular Observable inside another Observable

What is my goal? I have several components with similar checks and data manipulation activities. I aim to centralize these operations in an observable. To do this, I created an observable called "getData" within my service... The unique aspect of "getData ...

Troubleshooting issues encountered while sending HttpClient Get Requests from Angular Front-End to Node.js Back-End

I am encountering an issue where I keep getting the error message "Cannot GET /" on my local host URL when attempting to send a HttpClient get request from my Angular front-end to my Node.js back-end endpoint. Despite the fact that my back-end endpoint suc ...

Angular 2 decorators grant access to private class members

Take a look at this piece of code: export class Character { constructor(private id: number, private name: string) {} } @Component({ selector: 'my-app', template: '<h1>{{title}}</h1><h2>{{character.name}} detai ...

Angular2 filter array of objects

I am struggling to effectively filter through an array of objects. Can someone point out what I might be doing incorrectly? My Filter Pipe transform(value: any, args?: any): any { if (!args) return value; return value.filter(item => this.che ...

Debugger for Visual Code unable to locate URL in Microsoft Office Add-in

I recently installed the Microsoft Office Add-in Debugger VS code extension, but I'm having trouble getting it to work despite following the instructions. Every time I try, an error message pops up: https://i.sstatic.net/h2FYs.png Upon inspecting my ...

Looking to adjust the API response to fit the necessary JSON format for an Angular project?

A modification is needed in the API response to align with the required JSON format provided below. The current responses and the desired format are detailed for reference. Assistance is appreciated. The current representation of individual's data ne ...

A class member is not permitted to include the 'const' keyword

Having trouble with my ts code as I try to create a constant that can be easily changed by just modifying a simple element - but keep encountering the error that says "A class member cannot have the 'const' keyword." Here's the code snippet ...

What is the best way to handle and synchronize a dynamic number of actions?

I have developed an application that showcases a table of statistics regarding team members for all teams the current user is part of. The team list api provides an array of team ids when called. The team member list api requires a team id and returns a ...

What is the process for waiting on RxJS data and how should it be retrieved?

I am faced with a situation where I need to create a user through a function, but before proceeding with the creation process, I have to verify whether another user with the same userName is already present in the session: public createUser(form: FormGroup ...

Destructuring an object in the find method using TypeScript

I'm running into an issue with object destructuring: Property 'name' does not exist on type 'ItemType | undefined'.ts(2339) App.tsx import "./styles.css"; type ItemType = { id: number; name: string; }; export defaul ...

Using TypeScript, define a React function component by specifying its name as a type

While working in React.js, I encountered an issue with my Function Component. When I attempted to use the function name as the type, it resulted in an error. Here is a snippet of the code: import * as React from "react"; import { render } from "react-dom ...

Validating Dropdowns in React: An Essential Guide

I am in the process of developing a React-based application and incorporating Yup for validation. However, I am encountering a Cyclic Dependency error during the validation process. Description: Users will be presented with two dropdown lists of colors, v ...