No selection made in Angular2 dropdown menu

I can't seem to figure out what I am doing wrong. I am trying to get the value of a dropdown to be selected in my form. Here is the template-driven form I am using:

 <select class="form-control" id="role"
                                        required
                                        [(ngModel)]="user.role" name="role"
                                        #role="ngModel">
                                <option *ngFor="let user_role of user_roles" [ngValue]="user_role">{{user_role.display_name}}</option>
                                </select>

 this.user = new User(user_details.name,user_details.email,user_details.roles[0],user_details.is_confirmed,'','',user_details.image);

this is user_details.roles[0] :

[
  {
    "id": 1,
    "name": "admin",
    "display": "Administrator",
    "pivot": {
      "user_id": 6,
      "role_id": 1
    }
  }
]

I can't figure out the issue as to why the value is not being selected. After investigating, I suspect that it is because of the "pivot" object inside the [0] key. I tried removing "pivot" and it worked fine.

Answer №1

From my perspective, I would suggest using Events in this scenario. Here is a classic and straightforward example that you can draw inspiration from.

Imagine this as your HTML segment:

<select (change)="newValue($event)" class="" name="">
   <option value="val1">1</option>
   <option value="val2">2</option>
   <option value="val3">3</option>
   <option value="val4">4</option>
</select>

Next, let's consider the typescript section:

newValue(event: any){
    let value = event.target.value;
    console.log(value);
}

You can then assign the retrieved value to your desired attribute within the

this.user

object. I hope this explanation proves beneficial for your query.

Answer №2

Here are the steps you need to take.

<select class="form-control" id="role" [(ngModel)]="user.role" name="role">
    <option [selected]="user.role == **CHECK_YOUR_NAME_CONDITION_HERE**" value="user_role"> {{user_role.display_name}}</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

Generate a new perspective by incorporating two distinct arrays

I have two arrays containing class information. The first array includes classId and className: classes = [ {classid : 1 , classname:"class1"},{classid : 2 , classname:"class2"},{classid : 3 , classname:"class3"}] The secon ...

Tips on implementing href within HTML span tags while utilizing TSX syntax

Having recently started with Typescript and React, I am encountering an issue that I hope someone can help me with. In my code, there is a line that used to work perfectly fine when it was written in Javascript/React: <p><span href="#" id="nsTool ...

I need to search through a tree structure in typescript based on a specific value without encountering a maximum stack call exceeded error

How can I perform a value-based search on a complex tree structure in TypeScript without encountering the maximum stack call exceeded error? I am attempting to navigate through an expandable tree using TypeScript, and I will provide the code snippet below ...

Troubleshooting the dependency problem with @config-plugins/react-native-ble-plx

I am currently trying to install a package in order to utilize react-native-ble-plx on an expo app. However, I am encountering a dependency issue. Can anyone provide assistance with the following: npx expo install › Installing using npm > npm install ...

"React Bootstrap column showing gaps on the sides instead of filling the entire

In my current project with React and React Bootstrap 4.0, I am aiming to create a collapsible side-bar of 300px width on the left side of the screen, with the content displayed in the remaining space. The main parent component for the side-bar and content ...

The element is being implicitly assigned the 'any' type due to the inability to use a 'string' type expression to index the style type

I have encountered an issue that I am unsure how to solve: "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ prop_first: string; prop_second: string; }'. No index si ...

Implementing an Angular HttpInterceptor to improve caching efficiency for simultaneous requests by utilizing a shared observable

I am looking to implement caching for HTTP parallel requests by sharing the observable and also storing the response in a Map object. Check out the online demo caching-interceptor.service.ts import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest ...

Determine the data type of a variable based on the parameters of a function

A middleware function getSession(request, opts): void retrieves a session from the database and attaches it to the request, using specified opts. If the route is not secure, the function will exit early; If the route is secure and no user account is assoc ...

Troubleshooting Angular HTTP: Issue with the HTTP request headers not updating

// assigning the httpclient protected _http: HttpClient = inject(HttpClient); // defining the options for the request const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/tcc' }), observe: 'resp ...

Convert individual packages within the node_modules directory to ES5 syntax

I am currently working on an Angular 12 project that needs to be compatible with Internet Explorer. Some of the dependencies in my node_modules folder are non es5. As far as I know, tsc does not affect node_modules and starts evaluating from the main opti ...

Leveraging an angular service passed in as a dependency in a static function

Attempting to utilize an injected dependency within a static method poses a challenge, especially if the injected dependency is instance-scoped and cannot be accessed within the static method. Below is an example class: @Injectable() export class Passwor ...

Unable to set value using React Hook Form for Material-UI Autocomplete is not functioning

Currently, I am in the process of constructing a form using React-Hook-Form paired with Material-UI. To ensure seamless integration, each Material-UI form component is encapsulated within a react-hook-form Controller component. One interesting feature I a ...

The `Home` object does not have the property `age` in React/TypeScript

Hey there, I'm new to React and TypeScript. Currently, I'm working on creating a React component using the SPFX framework. Interestingly, I'm encountering an error with this.age, but when I use props.age everything seems to work fine. A Typ ...

Develop a React component with TypeScript that defines specific props in its interface, allowing its parent component to provide those props

I am looking to create a custom MenuButton interface that includes an "isMenuOpen" property, which can be provided by its parent component. function Menu({ SomeButton }: { SomeButton: MenuButton }) { const [isOpen, setIsOpen] = useState(false) retur ...

Creating a TypeScript NPM package that provides JSX property suggestions and autocomplete functionality for Intellisense

I developed a compact UI toolkit and released it on the NPM registry. The library is built using strongly typed styled-components (TypeScript) and can be easily integrated into React applications. It functions perfectly after installation with npm install ...

The name 'Firebase' is not recognized by Typescript

Encountering typescript errors while building a project that incorporates angularfire2 and firebase. Here are the packages: "angularfire2": "^2.0.0-beta.0", "firebase": "^2.4.2", Listed below are the errors: [10:58:34] Finished 'build.html_css&apos ...

Ways to apply CSS class styles when a button is clicked in Angular

How can I create a button that toggles between light and dark mode when clicked, changing the background color and font color accordingly? I need to add CSS classes .bgdark and .textlight to the 'mainbody' for dark mode. HTML <div cla ...

The attribute 'XX' is not recognized within the 'useState' type

I am facing an issue with an API call in my code. Here is a snippet where I receive the response and add it to the state using setInfo: const [info, setInfo] = useState([]) axios.post('/user', { data: 'data' }) .then(response => ...

Is it true that Async methods in Typescript return promises?

I'm currently in the process of familiarizing myself with Async/Await in Typescript. I've been updating existing code, for example: getImportanceTypes(): Promise<void> { return this.importanceTypeService.list() .then(i ...

Ensuring Redirection to Login Page Upon Refresh in React Router Dom

I have encountered a scenario where the customer needs to be directed to the login screen upon Browser refresh. For example: import "./styles.css"; import { Route, Routes, BrowserRouter as Router, Outlet, Link } from "react-router- ...