Use ng2-select2 directive to connect a reactive form formControlName

For managing forms in my Angular 5 project, I have implemented Reactive Form. Within the form, I integrated ng2-select2 to create a dropdown. However, when attempting to bind formControlName to the <select2></select2> directive, an error is thrown:

ERROR Error: No value accessor for form control with name: 'citizenship_id'

Below is the code snippet from my ngOnInit function in the .ts file:

ngOnInit() {
    this.jobId = this.route.snapshot.queryParams.jobId;
    this.detailForm = new FormGroup({
        date_of_birth: new FormControl(null, Validators.required),
        gender: new FormControl('', Validators.required),
        marital_status: new FormControl('', Validators.required),
        npwp_family_status_id: new FormControl('', Validators.required),
        citizenship_id: new FormControl('', Validators.required),
    });

    // Additional code for ajaxOptions and options...
}

And here is the corresponding code from my .html file:

<select2 [options]="options" formControlName="citizenship_id"></select2>

Answer №1

Although Select2 may not have built-in support for ReactiveForms, a clever workaround can be implemented:

By creating a hidden input linked to formControlName, you can ensure that the value of the select2 input is always synced with the hidden input.

If you need to pre-select a value retrieved from an API response, consider using an array variable with the selected value (e.g.:

[{id: 1, text: 'Selected Value'}]
) and then setting [value]="{selected_value_id}" in the select2 directive.

Credit goes to OP @DennyRustandi and @SunilSingh for sharing this helpful tip in the comments.

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

Utilizing Angular 2 Observable for showcasing a seamless flow of real-time information

Currently, my Angular 2 Web application is utilizing a Couchbase Server as its database. The data communication occurs through WebAPIs that interact with the CouchBase server. As of now, I am uncertain if this method is optimal, but I am constantly polling ...

The cdkDropListSortingDisabled attribute is not recognized as a valid property for the cdkDropList directive in Angular Material

I'm trying to achieve a specific use case where I need to drag and drop data from one zone (div) to another. After some research, I discovered that angular/material2 with the cdkDropList API could help me accomplish this task. Using the copyArrayitem ...

Tips for integrating Typescript Definition files with Visual Studio 2017

I have a challenge with my ASP.NET Core 2.0 application where I am attempting to incorporate TypeScript and jQuery. While TypeScript integration has been successful, I am facing issues with jQuery as it does not provide me with intellisense. Despite trying ...

typescript error: passing an 'any' type argument to a 'never' type parameter is not allowed

Encountering an error with newUser this.userObj.assigned_to.push(newUser);, receiving argument of type 'any' is not assignable to parameter of type 'never' typescript solution Looking for a way to declare newUser to resolve the error. ...

Ways to require semicolons in a Typescript interface

When declaring a TypeScript interface, both , (comma) and ; (semicolon) are considered valid syntax. For example, the following declarations are all valid: export interface IUser { name: string; email: string; id: number; } export interface IUser { ...

Configuration error with MultiCapabilities

Encountering an issue while utilizing multiCapabilities with two web browsers (Firefox and Chrome). Below is a snippet from my configuration: exports.config = { allScriptsTimeout: 11000, seleniumAddress: 'http://localhost:4444/wd/hub', b ...

Looking for help with getting ag-grid to work on Angular 2. Any new tutorials available?

Looking for a recent and effective tutorial for using ag-grid with Angular 2. The official website's tutorial is not working for me, any help would be appreciated. If anyone can provide some code examples as well, it would be really helpful. Thank y ...

Is there a way for me to indicate to my custom component the specific location within an input message where a value should be displayed

I'm currently developing a value selector component in ionic/angular and I've encountered an issue with the message/title that I want to pass to the component. I want to be able to specify where the selected value should appear within the message ...

One inventive method for tagging various strings within Typescript Template Literals

As TypeScript 4.1 was released, many developers have been exploring ways to strictly type strings with predetermined patterns. I recently found a good solution for date strings, but now I'm tackling the challenge of Hex color codes. The simple approa ...

Retrieve the key/value pair from a JSON response object using Angular 2 and TypeScript

return this._http.post(apiUrl, model) .map((res: Response) => { console.log(res.json()); let user = res.json(); //let user = Object.keys(res.json()); <-- only gives keys not values ...

(NG2-CHARTS) Unable to connect to the Chart Type as it is not recognized as a valid property for binding

I encountered an issue with my Chart Component where I am seeing the error message below. I have successfully imported ChartsModule into my app.module.ts file, but I am unsure why this error is occurring? Can't bind to 'ChartType' since ...

Difficulty in activating or deactivating form controls in Angular 2 upon receiving an HTTP response

When using formcontrol in Angular, I encountered an issue where I tried to disable the form control based on a variable assigned from an HTTP response. Angular2 gave me a warning message. The warning mentioned that it's not recommended to use the dis ...

Mastering the usage of Higher Order Components (HOC) with both types of props is

I am facing a challenge in implementing HOCs for this specific scenario. I aim to enclose existing components since they share similar functionalities. Below is an abridged version of my current structure: function CreateComponentHere(props: BaseProps): J ...

The present URL of Next.js version 13

When working with Next.js App Router in SSR, how can I retrieve the complete URL of the current page? I am unable to use window.location.href due to the absence of a defined window object, and using useRouter() does not provide access to the full URL. ...

Is there a way to transfer a variable from Angular 2 Frontend Express JS to an Angular 2 component?

After conducting thorough research, I have made specific modifications to my code. However, I am encountering some errors in my console that I cannot seem to resolve. Despite following a tutorial step by step. Your assistance would be highly valued as I a ...

Troubleshooting Issue: Relative Paths Fail to Work with routerLink in Angular 6

I seem to be encountering a problem with the Angular app I'm currently developing. It appears that when using relative paths with routerLink throughout the application, it fails to work properly. There are no errors thrown and the navigation does not ...

Utilizing the get and set methods to alter the structure of a string, but encountering the issue where the set method is

Upon receiving a datetime through an HTTP request, I need to format it before utilizing it. To achieve this, I utilize the get and set methods in my code. However, I noticed that the set method is never invoked. This is how my component (AdminComponent) l ...

Storing an array of objects in local storage is not working in Angular 9

I've encountered an issue trying to save an array of JSON objects into local storage, and I'm puzzled as to why it's not functioning correctly. Despite utilizing localStorage.setItem('comparisons', JSON.stringify(setComparisons)), ...

The node version in VS Code is outdated compared to the node version installed on my computer

While working on a TypeScript project, I encountered an issue when running "tsc fileName.ts" which resulted in the error message "Accessors are only available when targeting ECMAScript 5 and higher." To resolve this, I found that using "tsc -t es5 fileName ...

Why are the tabs in Angular displaying differently when the tab titles exceed 8 characters with Bootstrap 5?

Angular 14 Bootstrap 5 I developed a custom tabs component with pipes between the tabs that works flawlessly. However, I encountered an issue where the tabs slightly shift when the tab title exceeds 8 characters. Despite my efforts, I cannot pinpoint the ...