Tips for dynamically changing the selected option in a drop-down menu using Angular 5

Currently, I am encountering an issue while attempting to pre-select a value in a dropdown menu using Angular 5.

This is the HTML code:

<mat-form-field class="col-sm-3">
   <mat-select placeholder="State" name="state [formControl]="stateFormControl" required>
     <mat-option *ngFor="let state of states" value="{{state.key}}">{{state.name}}
     </mat-option>
   </mat-select>
   <mat-error *ngIf="stateFormControl.hasError('required')">State is required
   </mat-error>
</mat-form-field>

And this is the TypeScript code:

stateFormControl = new FormControl('', [
    Validators.required
]);

this.vendorForm.controls["state"].setValue(this.state);

Despite setting a default value in the FormControl declaration, the dropdown menu does not reflect this default selection. Assistance on how to resolve this would be greatly appreciated.

Answer №1

To connect to the value attribute in your <option> section:

<mat-select placeholder="State" name="state [formControl]="stateFormControl" required>
     <mat-option *ngFor="let state of states" [value]="state.key">{{state.name}}
     </mat-option>
</mat-select>

Answer №2

If you're looking for a solution, consider trying the following:

this.stateFormControl.setValue(this.state);

Alternatively, you can also explore this code snippet:

<mat-form-field class="col-sm-3">
   <mat-select placeholder="State" name="state" formControlName="state" required>
     <mat-option *ngFor="let state of states" value="{{state.key}}">{{state.name}}
     </mat-option>
   </mat-select>
   <mat-error *ngIf="stateFormControl.hasError('required')">State is required
   </mat-error>
</mat-form-field>

Should you decide to modify your HTML structure, you can refer to this tutorial on reactive forms.

In order to construct your form effectively, consider utilizing the following approach:

buildForm(){
    this.vendorForm = this.fb.group({
      state: ['', Validators.required ], // <--- You don't need to instantiate FormControls
    });
}

Moreover, ensure to include the following snippet in another part of your codebase:

<form [formGroup]="vendorForm">

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

CORS policy issue with Angular incorporating Agora shows "No 'Access-Control-Allow-Origin'"

I'm new to Angular and currently working on a demo app for proof of concept. The main focus is integrating the Agora SDK into Angular for video calls. I found an integration code for Agora in Angular on GitHub and implemented it as shown below. The `s ...

Guide on importing a custom CSS file from Syncfusion Theme Studio into an Angular project

Is there a way to incorporate custom scss files downloaded from Syncfusion Theme Studio into Angular CLI without adding the URL to the styles section in angular.json? Can we directly import it into styles.scss instead? I attempted to do so by including th ...

Using Bootstrap for Angular 10 Modal with Data Binding

I've come across an interesting concept in Angular that involves using @Input() to delve into nested components and then back out with @Output() events. It's a great idea, but why am I encountering two-way binding in my specific scenario? Any in ...

Troubleshoot an Office add-in using VS Code

Looking for guidance on Office add-ins and VS code... I recently went through the steps outlined in this tutorial by Microsoft to create an Excel custom functions add-in. To debug it using VS code, I had to select TypeScript as the script type while creat ...

Photo captured by camera is not stored in photo gallery

I am currently working on a basic image upload form that allows users to take photos using their phone camera and upload them. However, I have noticed that the pictures taken this way are not being saved to the gallery. Is there something missing in the H ...

Mastering the Art of Utilizing Generic Typing to Access Objects

I am trying to find a way to access an object by class using generic typing. The issue I am encountering is that I am getting an error when trying to check if the locators contain an input field. type '{ form1: { item2: { checkbox: string; input: st ...

Reorganizing components on the fly in Angular 5

Utilizing the ComponentFactoryResolver allows me to dynamically generate components, as detailed in the official documentation. // Every time this code is executed, a new component is created public buildComponent() { const factory = this.componentFacto ...

Typescript: Managing nested arrays of objects

I am working with a sample array of objects as shown below: let arr = [{id: 1,name: 'Test',segment: 'test',subCategory: [{id: 1,name:'Test1',segment:'test1'}]}] My goal is to reformat this array into the following s ...

Encountering an error with Mongoose's .pre('save') method in Typescript

Every time I attempt to use the hash password .pre hook, it refuses to save. userSchema.pre("save", async function (next) { let user = this as UserDocument; if (!user.isModified("password")) return next(); const salt = await bcry ...

Retrieve fresh information every 30 seconds utilizing the useQuery hook in React

I am utilizing '@tanstack/react-query' to retrieve data in my React + Typescript application. Below is a snippet of my code, where I aim to fetch metric data every 30 seconds import { useQuery } from '@tanstack/react-query'; import ...

Updating array values within the httpClient method in an Angular 14 application

Having trouble updating an array value using the httpClient method. I need to figure out how to access the updated array value outside of the httpclient method. Any assistance in finding a solution would be greatly appreciated. app.component.ts: public ...

Creating a Timestamp in JavaScript: A step-by-step guide

I have data from a Firebase database that requires processing before being returned in the same format. The Date of Birth field is retrieved in a Timestamp format, which I convert to a date, process, and then revert back to a timestamp using the code snipp ...

Error: The plugin "videoJsResolutionSwitcher" could not be located on AngularCli platform

Unable to recognize VideoJs-Resolution-Switcher as a Plugin! Issues: - Angular2 - Unable to find plugin: videoJsResolutionSwitcher - player.updateSrc is not a function Library Information: - videojs: https://github.com/videojs/video.js/ - vi ...

Tips for verifying internet connectivity and accessing stored data in localstorage

I'm working on my home.ts file and I need to use localStorage items when the internet connection is offline. However, I am encountering numerous errors when trying to add an IF condition in my code. Specifically, I want to access the getItem method be ...

What is the process of 'initializing' an object in TypeScript?

Is it possible that retrieving a json from a mongodb database and casting it does not trigger the typescript constructor? What could be causing this issue? I have a Team class export class Team { transformations: { [transformationId: string]: Transfor ...

Is it possible to programmatically trigger the OnChangeFile event in Angular without relying on a button click?

Is there a way to automatically trigger file upload to AWS without having to click the "choose file" button? Here is the code in my .html file: <div class="content"> <input (change)="onChangeFile($event)" type="file&quo ...

The data type 'Promise<string>' cannot be assigned to type 'string'

Is there a way to insert a variable response from a service and then show it on hover? Here is my attempt: toolTip: string; async mouseover(params) { this.handle = setTimeout(() => { this.toolTip = this.checkSaldo(10, 'FRA'); ...

Converting Typescript fat arrow syntax to regular Javascript syntax

I recently started learning typescript and I'm having trouble understanding the => arrow function. Could someone clarify the meaning of this JavaScript code snippet for me: this.dropDownFilter = values => values.filter(option => option.value ...

React Native Material - Implementing a loading indicator upon button press

With React Native Material, I am trying to implement a loading feature when a button is clicked. The goal is to show the "loading" message only when the button is active, and hide it otherwise. Additionally, I would like for the loading message to disappea ...

Executing ng server with --hmr results in a continuous reloading of the page during updates

After upgrading my Angular application to version 11.0.2, I decided to give the --hmr option on the CLI a try. Although it appears enabled from the CLI, any changes made to a page still result in a complete refresh in the browser. During compilation of th ...