Skip to main content

How to set selected option dynamically in Angular 6

All we use forms in our applications. Selects in Forms are great when you have multiple options. In Angular as a OPTION value we can use not only string literals, but also objects.
Simplest SELECT
<form [formGroup]="countryForm">
 <select formControlName="countryControl">
   <option [value]="country" *ngFor="let country of countries">             {{country}}</option>
 </select>
</form>
And in .ts file
countryForm: FormGroup;countries = ['USA', 'Canada', 'Uk']
constructor(private fb: FormBuilder) {}ngOnInit() {
 this.countryForm = this.fb.group({
   countryControl: ['Canada']
 });
}
After this we will have our SELECT with ‘Canada’ selected as default
That all is good, but what about having complex object as OPTION value, rather than a regular string. For that Angular provides [ngValue] directive.
Now let’s modify our countries array so instead of strings it will contain objects with country name, country currency code and unique property (id in this case)
countries = [{
 id: '8f8c6e98',
 name: 'USA',
 code: 'USD'
},
{
 id: '169fee1a',
 name: 'Canada',
 code: 'CAD'
},
{
 id: '3953154c',
 name: 'UK',
 code: 'GBP'
}]
Now as country is an object, in our template we need to display country.name for SELECT OPTIONS and also use [ngValue] directive as we are passing an object as a value.
<option [ngValue]="country" *ngFor="let country of countries">{{country.name}}</option>
Also to provide a default value we need to set one of objects from countries array.
this.countryForm = this.fb.group({
  countryControl: [this.countries[1]]
});
So now we have the same SELECT but now as a value we get not the name of the country, but whole country object.
Now let’s assume that we need to add an input where users can add more OPTIONS for this SELECT. We will have two inputs where users can add country name and country code. After that new OPTION will be added to our SELECT and that OPTION automatically will be selected. So usually all OPTIONS from SELECT come from the server, so in a real world example you also need to add new OPTIONS to the server, do a POST request and get brand new data. In this example i will simulate it with setTimeout.
So in template file
<input type="text" #name placeholder="Add country name">
<input type="text" #code placeholder="Add country code">
<button (click)="addNewOption(name.value, code.value)">Add to SELECT</button>
Add addNewOption() method in .ts file
addNewOption(name: string, code: string) {
  setTimeout(() => {
   this.countries = [
      {
        id: '8f8c6e98',
        name: 'USA',
        code: 'USD'
      },
      {  
        id: '169fee1a',
        name: 'Canada',
        code: 'CAD'
      },
      {
        id: '3953154c',
        name: 'UK',
        code: 'GBP'
      },
      {
        id: '68c61e29',
        name,
        code
      }
  ];this.countryForm.controls['countryControl'].patchValue(
     {id : '68c61e29', name, code}
  )
 }, 500)
}
So here we are getting values from two inputs and simulating call to server. As a result we are getting a new data containing countries (included one that we added) and assigning to countries array (ID was generated on ‘server’). After data was received we also use patchValue method to change the default value of our SELECT.
This is what will happen
So after submitting a new OPTION, it is there, but not selected. The reason of this is that Angular uses object identity to select options. So when we get a new data, objects will have different identities. Even that there is an object we provided in patchValue
{id : '68c61e29', name, code}
This object is not the same for Angular as the one that is inside countries array.
To solve this problem Angular provides compareWith input from SelectMultipleControlValueAccessor directive which is applied to our SELECT .
compareWithtakes a function which has two arguments: option1 and option2. If compareWith is given, Angular selects options by the return value of the function.
So first of all let’s write that function. Create a new function in .ts file
compareFn(c1: any, c2:any): boolean {     
     return c1 && c2 ? c1.id === c2.id : c1 === c2; 
}
And add this function to SELECT
<select formControlName="countryControl" [compareWith]="compareFn">
...
After this Angular will compare OPTIONS using their ids rather than object identifiers. As a final result we got what we expected

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...