Assign the chosen option in the Angular 2 dropdown menu to a specific value

Currently, I am utilizing FormBuilder in order to input values into a database.

 this.formUser = this._form.group({
   "firstName": new FormControl('', [Validators.required]),
  "lastName": new FormControl('', [Validators.required]),
  "externalCompany": new FormControl('', [Validators.required])
})

Prior to adding these values, I have a requirement to set the dropdown (external company) to a specific value that was previously submitted.

<select class="form-control" id="companyExternal" formControlName="externalCompany" (ngModelChange)=onChangeExternalC($event)>
     <option value="" >Select existing company...</option>
     <option value="{{company}}" *ngFor="let company of externalCompanies">{{company}}</option>
     <option value="Company name..." >ADD ANOTHER...</option>
</select>

I experimented with the following approach:

this._commServe.addExternalCompany(company).subscribe((data) => {   
  this.formUser.value.externalCompany = company.CompanyName;
}, (error) => {
  this.errorMessage = <any>error;
})

I also attempted to utilize ngModel, but this did not provide the desired outcome.

What would be the most effective method to establish the selected state of this dropdown without relying on jQuery, for instance?

Answer №1

To designate an option as selected in the model, you can apply the selected attribute.

[attr.selected]="selectedExternalCompany"

Implement this in the HTML template:

<select class="form-control" id="companyExternal" formControlName="externalCompany" (ngModelChange)=onChangeExternalC($event)>
     <option value="" >Select existing company...</option>
     <option value="{{company}}" 
         *ngFor="let company of externalCompanies" 
         [attr.selected]="selectedExternalCompany"
         >{{company}}</option>
     <option value="Company name..." >ADD ANOTHER...</option>
</select>

In the component, update the selectedExternalCompany when the select box changes, using it as the model.

Referencing the solution on How to add conditional attribute in Angular 2?

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

Is it possible to define a unique function signature in a child class when implementing a method from a parent class?

In the process of developing a repository module that includes generic methods, I have found that as long as each derived class has the `tableName` configured, the basic query for creating, finding, or deleting records remains consistent across all child c ...

Tips for showing more rows by clicking an icon within an Angular 2 table

When I click on the plus (+) button in the first column of each row, only one row expands. How can I modify it to expand multiple rows at a time? Thanks in advance. <div> <table class="table table-striped table-bordered"> <thead> ...

Tips for extracting year, month, and day from a date type in Typescript

I'm currently working with Angular 7 and I'm facing some challenges when it comes to extracting the year, month, and day from a Date type variable. Additionally, I am utilizing Bootstrap 4 in my project. Can anyone assist me with this? Below is ...

Efficiently process and handle the responses from Promise.all for every API call, then save the retrieved data

Currently, I am passing three API calls to Promise.all. Each API call requires a separate error handler and data storage in its own corresponding object. If I pass test4 to Promise.all, how can I automatically generate its own error and store the data in ...

Angular implementation for creating expandable table rows that reveal additional text when clicked

Hey there, I'm working on an Angular8 project that includes a table with a field containing a large amount of text, sometimes exceeding a hundred characters. I'm looking for some JavaScript code or an existing JS component that can help expand or ...

Pass information captured from Mat Dialog up to the main component

Looking for a way to pass true/false boolean data from a dialog box into the parent component without just console logging the result? You want to store it in a variable in the parent component for further use. Any suggestions on how to achieve this? This ...

The function angularCompiler.getNextProgram is not available in the context of angular 12 when using custom-webpack configurations

Recently, I upgraded my Angular 11 project to version 12. I have incorporated the @angular-builders/custom-webpack package in my devDependencies and I am using the below command for building my Angular project. ng build --configuration=production --build ...

Having trouble implementing ng2-charts in Angular 4 when using shared components

Using angular 4.0.0, angular-cli 1.2.1, and ng2-charts 1.6.0 has been a smooth experience for me so far. However, I encountered an issue when trying to incorporate ng2-charts into "shared" components. In my setup, I have a shared-components.module that is ...

Angular 5 - Inconsistent page refreshing when navigating instead of real-time DOM updates

I recently started a brand-new Angular 5 project and set up routing by following the instructions in the Angular Documentation. However, I encountered an issue where instead of updating the DOM, the page was refreshing when navigating between routes. Here ...

Ways to generate a unique link for every value in an option tag dynamically?

I'm currently working on a form that allows customers to buy an online service. Within the form, there's a dropdown list featuring 'select' and 'option' tags. This dropdown menu lets users pick a billing cycle (6 months, 1 ...

Is it feasible to differentiate generic argument as void in Typescript?

One of the functions in my code has a generic type argument. In certain cases, when the context is void, I need to input 0 arguments; otherwise, I need to input 1 argument. If I define the function argument as context: Context | void, I can still add voi ...

Extracting live TV channels from an m3u file by differentiating them from VOD content

Currently, I am developing an IPTV player app and have successfully parsed the m3u file. My current challenge is separating live TV channels from Video on Demand (VOD). I am unsure of where exactly the transition happens in the playlists. Below are the ke ...

Indulging in the fulfillment of my commitment within my Angular element

In my Angular service, I have a method that makes an AJAX call and returns a Promise (I am not using Observable in this case). Let's take a look at how the method is structured: @Injectable() export class InnerGridService { ... private result ...

Is it possible to implement typed metaprogramming in TypeScript?

I am in the process of developing a function that takes multiple keys and values as input and should return an object with those keys and their corresponding values. The value types should match the ones provided when calling the function. Currently, the ...

What is the process for generating an alert box with protractor?

While conducting tests, I am attempting to trigger an alert pop-up box when transitioning my environment from testing to production while running scripts in Protractor. Can someone assist me with this? ...

Angular 4 - Custom global error handler fails to capture Http errors

I have implemented a global event handler in my Angular application: import { ErrorHandler, Injectable, Injector } from '@angular/core'; import { Router } from '@angular/router'; @Injectable() export class GlobalErrorHandler implements ...

Difficulty Determining Literal Types that Expand a Union of Basic Data Types

Below are the components and function I am working with: interface ILabel<T> { readonly label: string; readonly key: T } interface IProps<T> { readonly labels: Array<ILabel<T>>; readonly defaultValue: T; readonly onChange ...

Switch between active tabs (Typescript)

I am working with an array of tabs and here is the code snippet: const navTabs: ITab[] = [ { Name: allTab, Icon: 'gs-all', Selected: true }, { Name: sources.corporateResources, Icon: 'gs-resources', Selected: false }, { Name ...

Unresolved issue with RxJS - Finalize not triggering

When attempting a logout request, I have encountered an issue where the same actions need to be dispatched regardless of whether the request is successful or fails. My initial plan was to utilize the finalize() operator for this purpose. Unfortunately, I ...

Achieve top-notch performance with an integrated iFrame feature in Angular

I am trying to find a method to determine if my iframe is causing a bottleneck and switch to a different source if necessary. Is it possible to achieve this using the Performance API? This is what I currently have in my (Angular) Frontend: <app-player ...