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,

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

arrange items based on their category into arrays

I have a JSON file that needs to be arranged based on three specific fields. Here is an example snippet of the JSON data: { "Racename": "10KM", "Category": 34, "Gender": "Male", "Work": "Google", "FullName": "Dave Happner", "Rank": 1, "Poni ...

The array does not yield any values when utilizing Angular CLI

Recently, I created a component that contains an array of strings. Here's the code snippet for reference: import {Component} from '@angular/core'; @Component({ selector: 'app-products-list', templateUrl: './products-list. ...

Toggle the disable state of a button depending on a specific condition

I have a scenario where I am fetching data from a server, and I need to apply a filter to a specific column. The requirement is that if the "bought" column (boolean) has a value of true, then the edit button should be disabled; otherwise, it should be enab ...

In Visual Studio, the .js.map files and .js files seem to be mysteriously hidden, leaving only the TypeScript .ts files visible

In the past, I utilized Visual Studio Code for Angular 2 development and had the ability to hide .js and .js.map files from the IDE. Now, I am working on a project using VS 2017 Professional with Typescript, Jasmine, Karma, and Angular 4. Task Runner, etc. ...

Identifying whether a particular area is represented in a geographic map array presents a significant challenge

Having an issue with typescript currently. I have a variable that contains different string entries representing x, y positions. The entries are as follows: ["3,3","3,4","3,5","2,3","2,4","2,5","-1,-2","-2,- 2","-2,-1"] My goal is to determine if this land ...

Discover the solution for resolving the issue of HttpErrorResponse 405 not permissible

I am currently managing a website on a VPS that relies on Flask as the backend API server, Angular for the frontend, and Nginx as a reverse proxy. The Nginx has SSL installed, but I am encountering an issue where I can only connect to the Flask server usin ...

Having issues with @ts-ignore in Typescript on a let variable that is not reassigned?

JOURNEY TO THE PROBLEM My current task involves destructuring a response obtained from an Apollo useLazyQuery, with the intention to modify one variable. In a non-Typescript environment, achieving this would be straightforward with just two lines of code: ...

Transform Observable RxJS into practical results

In a straightforward scenario, I have an upload action on the page that looks like this: onUpload$: Subject<SomeUpload> = new Subject<SomeUpload>(); uploadAction$: Observable<Action> = this.onUpload$.map(entity => this.someActionServi ...

Tips for sending props, state, or arguments to a TypeScript React component

Hey there, total newbie here... I'm currently working on a school project and I've hit a bit of a roadblock... I'm attempting to pass some props from one component to another, but for some reason, it's not working properly. The goal ...

Is it possible to encrypt data using a private key in Angular and then decrypt it using a public key in PHP using RSA encryption?

Attempting to Encrypt data using the RSA Public Key in Angular and Decrypt it with the public key in PHP. Encryption is done with the JsEncrypt library in Angular, while decryption takes place in PHP. :openssl_public_decrypt($signature, $decrypted, $public ...

Using Angular template to embed Animate CC Canvas Export

Looking to incorporate a small animation created in animate cc into an angular template on a canvas as shown below: <div id="animation_container" style="background-color:rgba(255, 255, 255, 1.00); width:1014px; height:650px"> <canvas id="canv ...

What is the best way to implement multiple templates for a single component?

Is there a way to configure my Home Component based on the user's role? For instance: If the employee is an admin, then the home component should load the template URL designed for admins. Likewise, if the employee is a cashier, then the home compo ...

What sets apart a class from a service in NativeScript?

I am embarking on the journey of learning Nativescript + Angular2, and while reading through the tutorial, I came across this interesting snippet: We’ll build this functionality as an Angular service, which is Angular’s mechanism for reusable classes ...

The service being injected is not defined

Two services are involved in this scenario, with the first service being injected into the second service like so: rule.service.ts @Injectable() export class RuleService { constructor( private _resourceService: ResourceService ){} s ...

Destructuring an object in the find method using TypeScript

I'm running into an issue with object destructuring: Property 'name' does not exist on type 'ItemType | undefined'.ts(2339) App.tsx import "./styles.css"; type ItemType = { id: number; name: string; }; export defaul ...

Learn how to manipulate Lit-Element TypeScript property decorators by extracting values from index.html custom elements

I've been having some trouble trying to override a predefined property in lit-element. Using Typescript, I set the value of the property using a decorator in the custom element, but when I attempt to override it by setting a different attribute in the ...

The options passed to createReadStream in TypeScript do not accept {start: 90, end: 99}

After updating to TypeScript 1.6.2, I encountered an issue with my call to createReadStream(). The problem arises because the type definition in node.d.ts does not recognize 'start' and 'end' in the options parameter. var st = fs.crea ...

What is the method for adding local images to FormData in Expo version 48 and above?

When working with Expo v47 and its corresponding React Native and TypeScript versions, FormData.append had the following typing: FormData.append(name: string, value: any): void An example of appending images using this code could be: const image = { uri ...

Generics-based conditional type that verifies entry properties

I developed a function that accepts an argument with two different architectures. I intentionally avoided enforcing rules to allow flexibility for the user, which is now causing me some headaches ...

Guide to connecting data from the backend to the frontend in the select option feature using Angular 9

I have a backend system where I store a number representing a selected object, which I am trying to display in a select option using Angular. Currently, the select option only displays a list of items that I have predefined in my TypeScript code using enu ...