Even with ngModel in place, Ng-Select fails to set a default value

Here is the HTML code I used:

<ng-select 
      [items]="sensorTypes"
      bindLabel="label"                 
      [multiple]="true"
      placeholder="Select"
      [(ngModel)]="selectedAttributes">
</ng-select>

The TypeScript code I implemented looks like this:

ngOnInit(): void {
    this.sensorTypes = [
      { label : "Power", value : "P"},
      { label : "Current", value : "C"},
      { label : "Voltage", value : "V"}
    ];
    this.selectedAttributes = [
      {label : "Current", value : "C"},
      {label : "Voltage", value : "V"}
    ]
  }

Despite the drop-down list working perfectly, the selectedAttributes are not selected by default. Upon page refresh, Current and Voltage are not automatically selected even though they are visible options.

Answer №1

I have always found simple HTML select to be effective, although I haven't used ng-select before.

<select class="custom-select" name= "anyName" [(ngModel)] = "myVariable"
 style = "width: 100%;">

      <option selected disabled>Choose administrative rights: </option>
      <option value="full">
        Full</option>
      <option value="partial">
        Partial</option>
      <option value="minimum">Minimum</option>
</select>

Answer №2

Use the bindValue parameter to bind the selected options value.

<ng-select 
      [items]="sensorTypes"
      bindLabel="label"
      bindValue="value"                 
      [multiple]="true"
      placeholder="Select"
      [(ngModel)]="selectedAttributes">
</ng-select>

By binding the sensorTypes object's value key, selectedAttributes will be an array of strings<value>.

To select Current and Voltage by default, initialize selectedAttributes as follows:

this.selectedAttributes = ["C","V"];

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

Ways to implement data pagination in an Ionic 4 application using ngx-pagination

I tried following the instructions on this page (https://www.npmjs.com/package/ngx-pagination) to integrate ngx-pagination into my Ionic app. However, I encountered an error indicating that the ngx-pagination package was not installed successfully. Are the ...

Troubleshooting: Angular2 RC5 router unable to locate lazy loaded module

I am facing an issue with my Angular2 RC5 test project that involves using routing to lazy load modules. Despite multiple attempts, I cannot seem to identify what is wrong with the project. Directories app |-about (contains about.module.ts and about.co ...

Angular Dynamic Form Troubles

Recently, I followed a tutorial from https://angular.io/guide/dynamic-form to create a dynamic angular form. So far, everything has been working smoothly. However, I am now facing a challenge as I try to implement a question type where users can add more i ...

Ways to have a Typescript generic inherit from a specific type

I'm facing an issue related to a component I have. const MyComponent = <T, extends { optionalProperty?: MyType }> When I try to call <MyComponent<SomeGeneric>>, I get this error message: Type 'SomeGeneric' has no properti ...

When it comes to TypeScript, one can always rely on either event.target or event

I'm a beginner with TypeScript and currently in the process of refactoring an arrow function within React.js. Here is the current implementation: handleChange = (event): void => { const target = event.target || event.srcElement; this.s ...

Concealing an element with Angular 2

Is there a way to hide only the selected row in this table instead of hiding the entire table? <tr *ngFor="let coll of pagedItems"> <template [ngIf]="hide"> <td><i title="Edit Collaborator" data-toggle=" ...

injecting stylish json into a textarea using angular

Seeking a way to enhance the appearance of the string in my angular text area, retrieved from the database. The data is stored as an object that is sent as a string and saved in the database. I tried using ang-jsoneditor for this purpose, but now I need to ...

Having difficulty retrieving a JSON Object value through an angular2 pipe

I am currently working on creating a dynamic table using Angular2. I have set up an Angular2 component with two pipes: the first pipe successfully retrieves the key from the JSON object, which is used as the column for the table. However, the second pipe, ...

Scrolling horizontally in Ionic framework

In regards to the response found on Ionic - Horizontal scroll tab for Categories, I have a question. I am curious about what needs to be included in the category.model. Can anyone provide some guidance? ...

Encountering a Typescript issue while utilizing day classes from Mui pickers

Recently, I encountered an issue with my code that alters the selected day on a Mui datepicker. I came across a helpful solution in this discussion thread: MUI - Change specific day color in DatePicker. Although the solution worked perfectly before, afte ...

Troubleshooting a NextJs/TS problem with importing ESM modules

Click here for the Code Sandbox I'm currently in the process of transitioning some code to NextJS 11 / Webpack 5, including certain modules that now exclusively support ECMAScript Modules (esm). Prior to the upgrade, I could easily export all files ...

Error: Unable to locate the type definition file for the '@babel' package

I am currently working on a new project and here is the content of my package.json file. { "name": "dapp-boilerplate", "version": "1.0.0", "main": "index.js", "license": "MI ...

Error message: "The property in question is not recognized on the specified type 'CustomEvent'"

I am currently using the latest version of Angular 2 and have encountered an issue with this code snippet: var passWidgetIdEvent = new CustomEvent("passWidgetIdEvent"); passWidgetIdEvent.widgetId = event.target.parentElement.id.replace("removeWidgetLink_" ...

When I hover over the content, the image displayed in the tooltip is causing a flickering effect

Dealing with Angular in this situation, my goal is to have an image or video displayed inside a tooltip when hovering over specific content. However, there seems to be a flickering effect before the image renders, making the transition less smooth compared ...

Issues with setting up rollupjs configuration

While compiling my TypeScript project with the provided configuration, I encountered an error message stating: "Error: When building multiple chunks, the output.dir option must be used, not output.file." Any assistance would be greatly appreciat ...

How can I incorporate a new function into a TypeScript class that already exists?

In my current angular 2 cli project, I am faced with the task of defining a plugin that does not have its own type definition. This plugin relies on a main library that already has its own typed definitions and is functioning properly. I have two files; t ...

Using Angular 5 custom validations in combination with Bootstrap 4 validation pseudo-classes (:valid, :invalid)

Bootstrap 4 validation styles are based on the classes form-control:valid and form-control:invalid. Angular provides the option to apply any custom class when a field is in error. If I adhere to the specifications outlined here: https://getbootstrap.com/d ...

Tips for assessing the prop that is being passed to a styled component with React and TypeScript

I am trying to apply a background color to a styled component div only if the state "active" is true. This is how I am currently attempting to do it: function Main() { const [active, setActive] = useState(false); return ( <ChildCompone ...

How can the value of a number in Angular be changed without altering its original value?

Imagine having the initial number 100. If I enter 50 in another input, it should add 50 to 100. However, if I then change the value from 50 to 80, the total should be 180 and not 230. The goal is always to add numbers to the original sum, not the new valu ...

Retrieving the Value of a Member in an Object using Angular

Is there a way to retrieve the value of an object in Angular using a variable as the member identifier? For example: --> my Angular class object: Object1 { name: foo property2: bar } --> my function: myFunction(memberName: string) { return Ob ...