Choosing a default selected value from a dropdown list with multiple editing options

When loading my "multiple edit" screen, I default the values as follows:

private createFormGroupItem(item: ...): FormGroup {
    return this.formBuilder.group({
      title: new FormControl(item.title, [Validators.required]),
      effectiveDate: new FormControl(item.effectiveDate, [Validators.required]),
      tariff: new FormControl(this.ddlTariff[0].tariffId, [Validators.required])
    });
  }

The title and date fields get filled with saved values, but I am uncertain about the syntax to have the saved value for Tariff dropdown selected.

Essentially, the FormControl is populated with records, and I want the one with the item.tariff value to be automatically chosen.

I found a stackblitz that demonstrates similar functionality, but I'm unsure how to adapt it to test with an actual object in my project.

Answer №1

Give this a shot

Initialize formgroup with default values:

this.formBuilder.group({
      title: new FormControl('', [Validators.required]),
      effectiveDate: new FormControl(new Date(), [Validators.required]),
      tariff: new FormControl(0, [Validators.required])
    });

Next, if your item model matches the formgroup property names and types, execute the following

this.[formgroup].patchValue(item);

The patchvalue function will populate the formgroup with values from your model,

If you are uncertain about the issue related to the ID being present in there,

https://i.sstatic.net/zcn3P.png

Answer №2

function generateForm(item: ...): FormGroup {

let exampleForm = this.formBuilder.group({
  title: new FormControl(item.title, [Validators.required]),
  effectiveDate: new FormControl(item.effectiveDate, [Validators.required]),
  tariff: new FormControl(this.ddlTariff[0].tariffId, [Validators.required])
});

exampleForm.controls.Tariff.patchValue(item.tariff.tariffId);

return exampleForm;
}

this function is successful

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

Tips for handling promises in a class getter method in TypeScript

In two of my classes, I use async/await functions to retrieve products from the product class. export default class Products { async getProducts() : Promise<[]> { return await import('../data/products.json'); } } export defa ...

Using ngIf for binding

Trying to bind values based on conditions specified in *ngIf. However, when using the && operator within *ngIf, it seems to be behaving mysteriously. Sample Code: <div *ngIf="days.sunday == true"> <p class="circle ml-3" ...

Is it necessary to install ng-bootstrap if my project was built using the Bootstrap 4 alpha theme in Angular 4?

I am currently utilizing the SB-Admin-BS4-Angular-4-master theme in Angular 4. The theme includes a link to . My goal is to implement Bootstrap modals in my code. Following the documentation provided in the theme, I integrated the modals as per instruction ...

Verify if all the words commence with a certain character using regular expressions

I am working on form validation using Angular, and I am trying to verify if all words in a string start with the letter 'Z'. I am implementing this using a pattern so that I can dynamically change the input's class. So far, this is what I h ...

The index signature for strings appears to be duplicated in this TypeScript file, causing an

I am attempting to create a type with an index signature in TypeScript. Here is the code snippet: export interface LoginState { account: { [userName: string]: string; [password: string]: string; }; } However, I ...

Tips for optimizing Angular source code to render HTML for better SEO performance

Our web platform utilizes Angular JS for the front-end and node js for the backend, creating dynamic pages. When inspecting the code by viewing the source, it appears like this: For our business to succeed, our website needs to be SEO-friendly in order to ...

Ensuring type safety in TypeScript arrow function parameters

I have encountered an issue with my code when setting "noImplicitAny" to true. import ...; @Injectable() export class HeroService { private _cachedHeroes: Observable<Hero[]>; private _init: boolean; private _heroesObserver: Observer<Hero[ ...

Keeping an Rxjs observable alive despite encountering errors by simply ignoring them

I am passing some values to an rxjs pipe and then subscribing to them. If there are any errors, I want to skip them and proceed with the remaining inputs. of('foo', 'bar', 'error', 'bazz', 'nar', 'erro ...

What are the best practices for implementing jquery owlCarousel within an Angular 4 component?

I've included my 'carousel.js' file like this: $('#owl-carousel-1').owlCarousel({...}); and in carousel.component.html, I have: <div id="owl-carousel-1" class="owl-carousel owl-theme center-owl-nav home- carousel">....< ...

Tips for sending parameters in Next.js without server-side rendering

I followed the documentation and tried to pass params as instructed here: https://nextjs.org/docs/routing/dynamic-routes However, I encountered a strange issue where the received params are not in string format. How is it possible for them to be in an arr ...

``Is there a specific scenario where the use of getInitialProps is recommended when automatically redirecting from one

Within my application, I have set up an auto-redirect from the root directory '/' to '/PageOne' with the following code: const Home = () => { const router = useRouter(); useEffect(() => { router.push('/pageone', ...

What is the best way to customize the styles of a reusable component in Angular2?

I am working with a reusable component called "two-column-layout-wrapper" that has its styles defined in the main .css file. In another module, I need to use this component but customize the width of two classes. How can I override these styles? import ...

Change the parent title attribute back to its original state

This is in contrast to queries similar to the one referenced here. In my scenario, there is a child element within a parent element (specifically a matSelect within a matCard, although that detail may not be significant) where the parent element has a set ...

How to create a beautiful grid layout using @angular/flex-layout, @angular/material, and mat-card to showcase stunning images

I have created a basic layout that looks like this: Cell 0 Cell 1 Cell 2 <!-- these are not to appear in actual render __________________________________ | Image 0 | Image 1 | Image 2 | |----------| Image 1 |----------- | text here| ...

"Enable email delivery in the background on a mobile app without relying on a server

I am currently in the process of developing a mobile app using Ionic. One feature I would like to incorporate is sending an email notification to admins whenever a post is reported within the app. However, I am facing challenges with implementing this succ ...

What are the recommended methods for dealing with arrays that have uniqueItems set to true in OpenAPI?

When I use OpenAPI Generator to generate Angular 12 code from JSON data produced by a Java application, an API model is created as follows: export interface UserDto { roles?: Set<RoleDto>; } The JSON file contains the following information: "U ...

Having trouble with setting a default radio button selection in an Angular form within Ionic 4 framework

I am currently working on an application using Ionic to design a form that includes radio buttons. I have been attempting to set one of the radio buttons as checked by default, but so far, nothing seems to be effective. I have tried various methods, such a ...

Tips for implementing pagination on a large JSON file without traditional pagination controls

Looking for the best way to implement pagination in a NextJs app that loads products from a local JSON file? This JSON file doesn't have any page properties, so the only option is to limit the number of products shown by using slice: {Object ...

How to store an imported JSON file in a variable using TypeScript

I am facing a challenge with a JSON file that stores crucial data in the following format { "login": { "email": "Email", "firstName": "First name", "lastName": "Last name", ...

Deleting a property once the page has finished loading

My issue is a bit tricky to describe, but essentially I have noticed a CSS attribute being added to my div tag that seems to come from a node module. The problem is, I can't seem to find where this attribute is coming from in my files. This attribute ...