Assign the primeng dropdown's value to the model in a reactive form

I am currently encountering an issue while populating a form that contains several PrimeNg dropdowns. To simplify, let's consider an example similar to the ones provided on their website.

<form [formGroup]="myFormGroup">
  <p-dropdown [options]="cities" formControlName="selectedCity"></p-dropdown>
</form>
this.cities = [
  {name: 'New York', code: 'NY'},
  {name: 'Rome', code: 'RM'},
  {name: 'London', code: 'LDN'},
  {name: 'Istanbul', code: 'IST'},
  {name: 'Paris', code: 'PRS'}
];

For instance, if a user selects a row from a table for editing, corresponding to a complex object with a City property, we need to programmatically select, let's say Rome, in that dropdown on the form.

I have attempted:

this.myFormGroup.get("selectedCity").setValue('Rome');

also tried:

this.myFormGroup.get("selectedCity").patchValue('Rome');

and even added to the html:

optionLabel="name"

However, nothing seems to be getting selected. Any suggestions on how to tackle this issue efficiently?

I believe I should refrain from adding

[(ngModel)]="selectedCity"

instead, do:

this.selectedCity='Rome';

Using Angular6 and PrimeNG 6.1.2.

Answer №1

It is important to note that the values in the options array are what will be set as the values for the FormControl.

In this scenario, the form control values consist of city objects since the cities array contains objects.

When setting the form control value programmatically, it must match one of the elements in the options array.

Therefore, if you wish to select "Istanbul," you need to set the exact same object from the cities array (specifically, cities[3])

This can be achieved as follows;

this.myFormGroup.get("selectedCity").setValue(this.cities.find(city => city.name === "Istanbul"));

Additionally, the attribute optionLabel="name" simply specifies which field in the city objects should be used as the display value.

For a demonstration, visit: https://stackblitz.com/edit/angular-6-template-6yu6jz

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

Navigate using history.push with user Logout Icon

Currently, I am utilizing a Material UI icon as a logout button in my project. Here is how I have implemented it: function logout(props:any){ localStorage.removeItem("token"); return( <Redirect to="/login" /> ) //props.history.push("/log ...

How can I convert an XML response to JSON in an Ionic 2 HTTP request

Hey there, I'm currently working on making an http request from this rss feed. Here's what I have so far: makeRequest() { this.http.get('http://www.gazetaexpress.com/rss/auto-tech/?xml=1') .subscribe(data => { ...

Typescript requires that the argument passed is undefined

Typescript: 2.4.1 I am exploring the creation of a helper function to produce redux action creators. Here is what I have: interface IAction<T extends string, P = undefined> { type: T; payload: P; } function createAction<T extends strin ...

The isAuthenticated status of the consumer remains unchanged even after being modified by a function within the AuthContext

I am working on updating the signout button in my navigation bar based on the user's authentication status. I am utilizing React Context to manage the isAuthenticated value. The AuthProvider component is wrapped in both layout.tsx and page.tsx (root f ...

Can you explain the meaning of `images:Array<Object> = [];` in TypeScript?

Recently, I stumbled upon this code snippet in TypeScript images:Array<Object> = []; I'm curious, what exactly does the "<>" notation signify? ...

Angular is having issues with the positionClass 'toast-bottom-right' not functioning properly

The 'positionClass: 'toast-bottom-right' is not overriding the default 'positionClass: 'toast-top-right' class as seen in the following code: 'this.toastr.success('Your Screen as Set to Default[enter image descripti ...

Error occurring with the gulp task runner

Encountering an error while using the task runner for my "gulp" file. My project involves Angular 2 and Asp.net Core. The "typings" folder is set up with a "typings.json" file that contains the following: { "resolution": "main", "tree": { "src": ...

When the page loads, the ngOnInit() function does not trigger the login.html file

I am currently working on developing a login page for my Nativescript and Angular 9 based application. I have successfully tested user input functionality and API response triggers, but there are some issues that need to be addressed. login.service.ts imp ...

Using a functional wrapper component to reset the modal field in Reactstrap upon closing and reopening

In the main component that displays a list of to-do tasks, we have the ability to add or edit existing tasks. To facilitate this functionality, a separate wrapper was created. import React, { useEffect, useState } from 'react'; import { Label ...

Solving issues with event handling through addEventListener within a functional component in React

I am working on a React component that includes an input field and I want to implement a character autocompletion feature. The idea is that when a user types " or ', the same character should be automatically added again, with the cursor placed i ...

Having trouble syncing ionic and capacitor - npm keeps throwing an error

In my blank Ionic project, I am attempting to integrate Capacitor with Ionic in order to build an Android app. When I run the following command: ionic capacitor add android, I encounter an npm error. Can someone please assist me in resolving this issue? C ...

Enhancing search capabilities in Angular 8.1.2 by filtering nested objects

I am in need of a filter logic similar to the one used in the example posted on this older post, but tailored for a more recent version of Angular. The filtering example provided in the older post seems to fit my requirements perfectly, especially with ne ...

Is there a way to prevent QtLinguist from opening every time Visual Studio tries to display a TypeScript file?

Ever since I installed Qt tools for Visual Studio, my Ctrl+click on a class name triggers Qt Linguist: https://i.stack.imgur.com/USAH1.png This hinders me from checking type definitions, even though Visual Studio has already parsed them. The type informa ...

Enhancing RxJS arrays of Observables with supplementary data for preservation

Question: Processing Array of Observables with Metadata in Angular How can I process an array of Observables, such as using forkJoin, while passing additional metadata for each Observable to be used in the pipe and map functions? const source = {animal: & ...

Unable to access 'export default class extends Vue' in the template

I've recently started using Vue.js with TypeScript, but I'm having trouble accessing values from outside the class. @Component({ name: 'SidebarItem', components: { SidebarItemLink } }) export default class extends ...

When changing the dropdown option on a separate page in React/Next JS, all checkboxes show the clicked style as a result of utilizing useState

I have implemented checkboxes for three different categories: "Types", "Price", and "Categories". They function correctly, with data being passed to a separate checkbox component without any issues. The problem arises when I click a checkbox and then inte ...

Old version of Nativescript appium testing being installed ORAn outdated

I am in the process of creating a mobile application using nativescript + angular, and I am currently testing it with Appium. However, when I execute end-to-end tests using the following command, it seems to load an older version of my app. tns build andr ...

Transforming a mongodb operation into an asynchronous function using await and async syntax

After calling the function to retrieve data from MongoDB, an undefined error occurs. It is suspected that converting the function to an async/await function may resolve this issue. However, there is uncertainty on how to make this conversion without disrup ...

What are the steps to incorporate a 3D scene into a React website?

Can I get some advice on how to create a React web application using TypeScript? I want to be able to click a button and have it show a new page with a scene of a town. What is the best way to achieve this in my React project? I've heard about using R ...

The module '@angular/compiler-cli/ngcc' is missing and cannot be located while trying to run ng serve

Out of the blue, I started encountering this error. It seems to be related to a version issue with angular-cli, but I'm unable to pinpoint the exact problem. Any assistance would be greatly appreciated! npm i displays some warnings and one compiler e ...