Using ngx-formly in Angular 11 for advanced form selection with ng-select

Currently, I am experimenting with ng-select and ngx-formly within Angular 11 by following the tutorials provided in the official documentation.

However, my implementation is resulting in errors that can be viewed here: https://i.sstatic.net/rc0PH.png

I would greatly appreciate any assistance in identifying where I may have gone wrong in my code or if there are any missed steps in my process.

Below is an example of my current implementation:

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { FieldType } from '@ngx-formly/core';

@Component({
    selector: 'formly-ng-select',
    template: `<div class="mat-input-infix mat-form-field-infix">
    <ng-select
       [items]= "(to.options|formlySelectOptions:field|async)!"
       [placeholder]="to.label || 'placeholder'"
       [bindValue]="to.bindValue || 'value'"
       [formControl]="formControl">
    </ng-select>
  </div>`
})
export class NgSelectFormlyComponent extends FieldType {
  formControl!: FormControl;}

The custom template shown above is used in my main component as demonstrated below:

fields: FormlyFieldConfig[] = [
 {
    key: 'nationId',
    type: 'my-autocomplete',
    // type: 'select',
    templateOptions: {
      label: 'Nation',
      options: this.dataService.getNations()
    }
  }]; 

In addition to this implementation, I have included it in my app.module configuration as outlined below:

FormlyModule.forRoot({
 types: [{
   name: 'my-autocomplete',
   component: NgSelectFormlyComponent,
    // wrappers: ['form-field'],
 }]
})]

Answer №1

For my solution, I needed to assign the available choices as an Observable to a component's variable and then access this variable from the template in order to display the options using the Async pipe.

I introduced a "loaded" state to control when the HTML should be rendered after the observable has been set.

Interestingly, the compiler was unable to recognize T[] | Observable as the types for Formly options.

Here is a snippet of the code:

export class MyComponent extends FieldType implements OnInit {
    options$: any;
    loaded = false;

    constructor() {
        super();
    }

    ngOnInit() {
        this.options$ = this.to.options;
        this.loaded = true;
    }

}

Component Template:

<ng-select ..>
    <ng-option *ngFor="let option of options$ | async">...</ng- 
    option>
</ng-select>

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

Splitting a td tag into multiple columns dynamically with Angular

I am attempting to dynamically split the table element into separate columns. My desired layout should resemble this: https://i.sstatic.net/C81tg.png The values for name and surname are fixed at 1, but the values for subjects and grades can vary (there ma ...

The combination of Threejs blending techniques with perspective and orthogonal matrices creates a

I am trying to align a perspective camera and an orthogonal camera in the same position and orientation, with the zfar plane set to the same value. However, despite having the same near and far values, I am encountering discrepancies in the z values and ...

How to set up 'ng serve' command in Angular to automatically open a private browsing window?

I am looking for a way to open my project in an Incognito Mode browser without storing any cache. Is there a specific Angular CLI flag that can be included in the ng serve -o command or in the Angular CLI configuration file to enable opening a browser in ...

Within my component, I have incorporated two datepickers. My goal is to emit an object containing the values of both the start date and end date (referred to as startDateValue and

I have attempted to tackle this issue, but I am encountering the problem of receiving the same date value for both inputs. export class DateComponent implements OnInit { @Input() startDate: string; @Input() endDate: string; @Output() sendDate: Event ...

How to retrieve a random element from an observable array within an Angular template

I'm attempting to randomly select an element from an Observable array to utilize in the template. I currently have the following setup: @Select(SomeState.tiles) tiles$: Observable<Tile[]>; and getRandomTile$(): Observable<Tile> { return ...

Need a cancel button to discard any edits made to a particular row

I'm working on an angular project where I have an array retrieved from a database displayed in a table. When a row is clicked, it switches from a display component to an edit component using ngSwitch. In the edit component, I'm trying to add a bu ...

When attempting to access an array element by index, it is returning as null

I have a script that extracts the dimensions of an image: getImageDimensions(file: File): Number[]{ let dimensions : Number[] = []; let _URL = window.URL || window.webkitURL; let img, file; file = fileUploaded; img = new Image(); ...

The status of the 'slider' may be 'undefined'

I'm really struggling to figure out how to resolve this issue, even though I suspect it's a simple fix that's eluding me... Here is the part of my code in TypeScript that's causing the error: const slideLeft = () => { cons ...

Converting a string into a component name (class name) in Angular 2

How can I convert the string "BoxOneComponent" into a class name BoxOneComponent in Angular 2? Is there a method similar to .toString() that allows for typecasting to a class name? ...

User instance does not function with the binding

When text is entered into the text box, the Angular form value changes but the userModel value remains the same , always displaying [Vino] as the userModel value. Below is the code from app.component.html, <form #userForm="ngForm"> {‌{userFor ...

Could anyone assist me in defining this particular typescript?

for (let i = 0; i < 10; i++) { setTimeout(function() { console.log(i); }, 100 * i); } Upon execution, it prints the following output sequentially: 0 1 2 3 4 5 6 7 8 9 However, the concept of multiplying i by 100 in the setTimeout function may s ...

When a React component in TypeScript is passed as a parameter and then assigned to a variable, an error with code TS2604 may occur stating that the JSX element type does not

I am currently facing an issue with handling props of a passed React Element in my Factory. I am getting a TypeScript error that says: TS2604: JSX element type 'this.extraBlock' does not have any construct or call signatures. This is my Child co ...

Issues arise with Jest tests following the implementation of the 'csv-parse/sync' library

Currently utilizing NestJs with Nx.dev for a monorepo setup. However, I've come across an issue after installing csv-parse/sync - my Jest tests are now failing to work. Jest encountered an unexpected token Jest failed to parse a file due to non-stand ...

Sending multiple types of data objects, including files, through a multipart data

Attempting to send multiple files to my REST API using PrimeNG: <p-fileUpload #fileInput name="myfiles[]" customUpload="true" (uploadHandler)="myUploader($event)" multiple="multiple" accept="*" maxFileSize="2000000" ...

The feature similar to SignalR is currently experiencing technical difficulties and is not

In my application, I have implemented a like functionality for posts. To achieve real-time updates on the number of likes, I explored SignalR and attempted to integrate it into my code. Unfortunately, despite not encountering any errors, the automatic upda ...

The properties '{ label: string; value: string; }' are required in type 'readonly never[]' for react-select, but they are missing

state = { groupPermissionValue: {label: '', value: ''}, } <Select instanceId="user-group" onChange={this.selectUserGroupOption} value={this.state.groupPermissionValue} options={this.state.groupPermission} i ...

Troubleshooting: HTTP client post request working with body.set but not with formData.append for sending data to API

I am in the process of updating the UX for an older application with APIs developed in ASP.NET When I make a POST request as shown below, everything works perfectly. The data is received: var APIURL = sessionStorage.getItem('endpoint') + "/ ...

generating declaration files for components with accurate type definitions from propTypes

I am in the process of creating a react/js library using rollup. My approach involves utilizing typescript to generate declaration files for my components. Despite having propTypes defined for my components, I have noticed that the emitted .d.ts files as ...

utilize undefined files are assigned (Typescript, Express, Multer)

I am facing an issue while trying to save image uploads to a folder named "/images". The problem lies in the fact that req.files is appearing as undefined for some reason. Below is the relevant code snippet. Feel free to ask any questions, any assistance w ...

Having trouble getting Lodash find to work properly with TypeScript overload signatures

I have been attempting to utilize _.find in TypeScript on an Object in order to retrieve a value from this object. The original code snippet looked like this: const iconDict = { dashboard: <DataVisualizer />, settings: <SettingsApp /> ...