Tips for retrieving selected values from local storage

I am working with a select component as shown below:

<label>
{{ "HOME.SELECT" | translate }}
<select #langSelect (change)="translate.use(langSelect.value)" (change)='onOptionsSelected($event)'>
  <option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="??">
    {{ lang }}</option>
 </select>
</label>

Within the constructor, the selected language is stored in localstorage like this:

constructor(public translate: TranslateService) {
  translate.addLangs(["en-US", "fr-FR", "de-DE"]);
  if (localStorage.getItem('language')) {
  translate.setDefaultLang(localStorage.getItem('language'));
  translate.use(localStorage.getItem('language'));
} else {
  translate.setDefaultLang('en');
  translate.use('en');
  localStorage.setItem("language", "en");
}
}

I'm looking for a way to automatically set the selected index in the dropdown based on the value stored in localstorage. Can anyone help with this?

Answer №1

Ensure to include the 'value' parameter in the select tag and pass a variable to it as shown below. Set the value of the variable as the localStorage value. Also, assign the same variable to 'selected'.

Here is the updated version of your code:

<pre>
  <label>
    {{ "HOME.SELECT" | translate }}
    <select #langSelect (change)="translate.use(langSelect.value)" (change)='onOptionsSelected($event)' value="localStorageValueVariable">
      <option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="localStorageValueVariable">
        {{ lang }}</option>
     </select>
    </label>
</pre>

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

Guide on integrating PHP and Angular development in your web application

Is it required to have all PHP files in the same Angular project when using Angular with PHP? Or should the PHP files only be located inside the XAMPP folder www? Thank you for your assistance. ...

Encountering issues while trying to run npm install for an Angular 7 application, specifically receiving an error stating: "Module not found: @angular-devkit/build-ng-packagr." This error is hindering

I don't have much experience with JavaScript, node, npm, Angular, etc. My expertise lies in TypeScript as I am still a beginner. However, I recently inherited an application that requires maintenance to resolve a cross-site cookie issue. As I attempt ...

Error: TypeScript is flagging that you can only specify known properties in an object literal, and the property '...' does not exist in the type 'DeepPartial<Document>'

I've been working on building a basic controller API in NodeJS with TypeScript, but I'm encountering the error ts(2345) while trying to assign values to the model. This is my user model: import mongoose, {Schema} from 'mongoose' cons ...

Troubleshooting Angular testing using Jest: Problem encountered with triggerEventHandler

I'm currently working on an Angular application and testing it with JEST. Everything seems to be running smoothly until I encounter an issue with event interactions in Angular. The test below works as expected: it('should delegate click to comp ...

Encountering the npm ERR! ERESOLVE error while trying to npm install in my Node project has been a frustrating issue

Upon running npm install in my project, I encountered the following error: npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead. npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While ...

Struggling with loading an image in Angular 6 with cornerstonejs

Just dipping my toes into the world of Angular 6. I'm currently grappling with integrating cornerstonejs into my Angular 6 project. However, all my efforts seem to hit a snag with this error message: The dreaded error TS7016: Could not find a decla ...

What is the best way to send confidential query parameters to a route in Angular 5?

One method currently used in Angular to transmit data to a route is by including it within the routes themselves. For example, in the tour of heroes guide found on the official Angular documentation, an id is sent to the hero component through the route h ...

Leveraging CSS nth-child selector in conjunction with ngFor in angular2

Looking for a way to style odd and even rows differently in my dynamically generated table using ngFor directive in angular2. *ngIf="AreThereMyOldMessages" *ngFor="let oldm of MyOldMessages;let i=index" *ngIf="AreThereMyNe ...

The context of EmbeddedView is established by passing an observable

I have a templateRef: @ViewChild('myTemplate', { read: TemplateRef, static: true }) myTemplate!: TemplateRef<unknown>; and viewContainerRef: @ViewChild('vcr', { read: ViewContainerRef, static: true }) vcr!: ViewContainerR ...

What is the best way to handle closing popups that have opened during an error redirection

In my interceptor, I have a mechanism for redirecting the page in case of an error. The issue arises when there are popups already open, as they will not automatically close and the error page ends up appearing behind them. Here's the code snippet re ...

Enhancing Angular Form Control with ASP.NET Core 7 Web API Date Serialization

The Person class has a property called Birthday, which is defined as type DateTime. public class Person { public string Name { get; set; } public DateTime Birthday { get; set; } } Within my controller, I have an endpoint setup like this: [HttpGet( ...

Error: Unable to locate module pathway in eslint/typescript configuration

My .eslintrc.json configuration is: { "env": { "browser": true, "commonjs": true, "es6": true, "node": true, "jest": true }, "parserOptions ...

Angular 2: Dealing with Stripped HttpHeaders in HttpResponse - Solutions and Fixes

Despite my efforts, I have been unable to find relevant documentation or examples that can help me solve this issue. When I send a request to my test rails server, the response only includes 2 headers. However, when using a REST test tool like postman, I ...

Ways to ascertain if a TypeScript type is a specific value

Can a utility type be created to identify whether a type is a literal value? For example: type IsLiteral<T> ... type IsStringALiteral = IsLiteral<string> // false type IsStringLiteralALiteral = IsLiteral<'abc'> // true type IsS ...

Will the enhancement of the artifact limit in DevOps have an effect on current pipelines and configurations?

Running pipelines on Azure DevOps is presenting me with error 402 Payment Required - GET https://pkgs.dev.azure.com..... and npm install failed. I have exceeded the artifacts free limit of 2GB, could this be causing the issue? If I upgrade the free artif ...

The state is not being updated immediately when trying to set the state in this React component

Currently, I am working on a React component that is listening to the event keypress: import * as React from "react"; import { render } from "react-dom"; function App() { const [keys, setKeys] = React.useState<string[]>([]); ...

Incorporating Angular 6 and NodeJS 8.4 with the MEAN stack, I aim to display the current status of all identifiers stored in MongoDB directly onto the browser

After successfully storing the list of objects in MongoDB, I have implemented a functionality to display all items on the browser. When the inventory button is clicked, the routerlink is used to fetch the availability and list them accordingly. Now, I am ...

No versions for "cra-template-typescript" that align with "latest" were located in our cache

Currently attempting to follow the steps outlined in this helpful guide: How to Develop a Basic React Application With an Express API. However, upon executing the command: npx create-react-app react-express-app --template typescript I encountered the foll ...

Encountering the error message "Receiving 'Multiple CORS header 'Access-Control-Allow-Origin' not allowed' while accessing my Laravel API from Angular"

After successfully developing an API with Laravel that functioned perfectly with Postman, I am now working on its front-end using Angular. However, I keep encountering this error every time I send a request to the API: Cross-Origin Request Blocked: The Sa ...

Choosing custom element children once they're connected to the DOM: A guide

My goal is to retrieve the value of transaction-name__inputbox when the user clicks on the transaction-add__button. The function transactionAddHandler is triggered upon clicking the button. However, my attempt to select this element using document.querySe ...