Displaying the preselected option in a Select dropdown menu using Angular

Here is the code snippet I have:

<select label="people" id="ppl"  [(ngModel)]="Selectedppl" (ngModelChange)="onPplSelection($event.target.value)">
<option>select people</option>
<option *ngFor="let x of peopleList" [ngValue]="x">
    {{x.name}}
</option>

I am dealing with a list of objects that contain properties such as name, address, and contact. My goal is to pass the entire object as a parameter to ngModelChange using ngValue.

Furthermore, once a specific person has been selected and saved, I would like the dropdown menu to display the name of the selected individual. Essentially, I want the default selected option in the dropdown to reflect the saved value.

It's important to note that I am not utilizing Reactiveforms in this scenario.

Answer №1

You can obtain the element's reference and pass its value to a function.

<select label="people" id="ppl" #ppl="ngModel"  
   [(ngModel)]="Selectedppl" 
   [compareWith]="compareFn"
   (ngModelChange)="onPplSelection(ppl.value)">
     <option>select people</option>
     <option *ngFor="let x of peopleList" [ngValue]="x">
       {{x.name}}
     </option>
</select>

ts

If you have a complex object, then you must use compareFn to help Angular compare the objects and set the default value.

  compareFn(a, b) {
    if (!a || !b) {
      return false;
    } else {
      return a.name === b.name;
    }
  }

See the working example here - https://stackblitz.com/edit/hello-angular-6-2z9f3b

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

Neglecting to review the CSS - embracing ejs layouts in Express

I am encountering an issue with the express ejs layouts where only the mainPage is able to read the CSS, while the other pages are unable to do so (even though the HTML reads it). Additionally, if I want to use another layout such as "layout2.ejs", what s ...

Tips for organizing MUI Card effectively within a React application using TypeScript

Struggling to build a React card component with Material-UI (MUI) and TypeScript that represents a car? The card should contain text, an image, checkboxes, a rating, and a button. Here's the code I've come up with so far: import React from ' ...

Reorganizing Firebase data in Ionic 2

I am currently working on an exciting project to develop an Ionic notes application, where users can easily rearrange items in the list using the reorderArray() function. However, I encountered an issue with Firebase resulting in an error message related t ...

Creating a dynamic step animation with jQuery: A step-by-step guide

Struggling to find resources on how to animate a color wheel using jQuery? Want to create a spiraling effect by gradually revealing colors at 45-degree intervals, like a loading GIF spiral? I need it to cycle through the defined colors in order and then cl ...

Generating React components dynamically can bring flexibility and efficiency to the

Looking for a solution to dynamically render different components based on the arguments passed with data. While using regular or React.createElement(Item) works fine, all other options seem to fail. http://jsfiddle.net/zeen/fmhhtk5o/1/ var React = windo ...

Compiling TypeScript to JavaScript with Intellij IDEA while preserving the folder hierarchy

Seeking assistance with maintaining directory structure when compiling Typescript to Javascript in Intellij Idea. The current directory setup is as follows: root - ts - SomeClass1.ts - SomeFolder - AwesomeClass2.ts - tsc The desired compiled file ...

Responses were buried beneath the inquiries on the frequently asked questions page

My FAQs page is in pure HTML format. The questions are styled with the css class .pageSubtitle, and the answers have two classes: .p1 and .p2. Here's an example: <p class="pageSubtitle">Which Award should I apply for?</p> <p class="p1" ...

Identification of input change on any input or select field within the current modal using JavaScript

My modal contains approximately 20 input and select fields that need to be filled out by the user. I want to implement a JavaScript function to quickly check if each field is empty when the user navigates away or makes changes. However, I don't want t ...

Creating a Yeoman application with a personalized Node.js server

As I embark on the journey of developing a node.js and angular application using the powerful Yeoman tool, I can't help but wonder about one thing. Upon generating my application, I noticed that there are predefined tasks for grunt, such as a server ...

Encountering numerous TypeScript errors due to a JavaScript file in Visual Studio 2017

Kindly review the update below I utilized the following package as a foundation for my VS Project -> https://github.com/AngularClass/angular2-webpack-starter Everything ran smoothly in Visual Studio Code, but when I attempted to convert it into a Visu ...

What is the process for configuring vue.config.js with typescript?

Just starting out with typescript and running into an issue while configuring vue.config.js const webpack = require("webpack"); module.exports = { plugins: [ new webpack.DefinePlugin({ __VUE_I18N_FULL_INSTALL__: true, __ ...

Step-by-step guide on building a factory in Angular for a pre-existing service

Currently, I am delving into the world of angularjs and exploring articles on service and factory functionalities. One particular example that caught my attention is showcased in this ARTICLE, which includes a demonstration using a Service Fiddle. As I de ...

JavaScript vanilla can be difficult to grasp, especially when it comes to

I'm experiencing a delay in displaying and hiding the mobile menu and table of contents section on my website when viewed on a mobile device. I'm using vanilla JavaScript to add and remove classes, but it's taking about one second for the me ...

Leveraging Watchers on props in Vue 3's Script Setup

When passing a prop to a component that declares its state, I am attempting to watch the prop and set the CSS styling accordingly. However, for some reason it is not working as expected. Can anyone help me figure out what might be wrong? <script setup ...

Adding a PDF generated from an HTML div to an email using Java

I am looking for a solution to convert the contents of an HTML div tag into a PDF file while preserving its associated CSS. This is essential as I will be using Java on the back-end to send emails, and I need to attach the PDF with the CSS intact when send ...

Troubleshooting Angular 7 Build Failure: Missing Typescript .d.ts Declaration Files for Ahead-of-Time Compilation

I have encountered difficulties in building my Angular 7 application after upgrading from v6. When I use ng build, everything runs smoothly. However, when I try either ng serve --aot, ng build --aot, or ng build --prod (which also includes aot), an error ...

User authentication on AngularJs is only initiated on the second interaction

My personally built AngularJs user authentication system is experiencing an unusual issue. While everything seems to be working fine - I can login, check access for specific pages, etc. - there is a strange behavior with the token authentication. It seems ...

Struggling with verifying the visibility of multiple elements using the toBeVisible() assertion

While running a test in debug mode, I've observed that toBeVisible() fails when it detects multiple elements. Interestingly, toBeVisible without the parenthesis passes the assertion in such cases. I'm facing a specific scenario where I need to p ...

Using a Regex Pattern to Validate Password Strength

var pattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()~])[a-zA-Z0-9!@#$%^&*()~]+$/; var password = document.getelementbyId("txtPassword").value; if(!pattern.test(password)) { alert("Invalid Password. Please make sure it contains at ...

Ways to obtain a referrer URL in Angular 4

Seeking a way to obtain the referrer URL in Angular 4. For instance, if my Angular website is example.com and it is visited from another PHP page like domaintwo.com/checkout.php, how can I detect the referring URL (domaintwo.com/checkout.php) on my Angul ...