Trigger event when ngModel changes

Currently, I am trying to perform a test on a select element...

  <select [ngModel]="selectedRouters" name="routerName" class="form-control" id="routersSelect" size="12" (ngModelChange)="selectRouters($event)" multiple>
    <option [value]="router.name" *ngFor="let router of routers$ | orderBy : 'name'">
      {{router.name}}
    </option>
  </select>

This test is done with a method that looks like:

selectRouters(routers) {
    this.routers$
        .filter(router => routers.includes(router.name))
        .forEach(router => router.setSelected(true))

    this.routers$
        .filter(router => !routers.includes(router.name))
        .forEach(router => router.setSelected(false))
}

The issue lies in the fact that the method expects a string[], and I'm unsure how to properly test this...

//initialization
component = fixture.componentInstance

//testing
component.selectedRouters = Array.of(r.name);

let evt = document.createEvent('Event');
evt.initEvent('ngModelChange');

selector.dispatchEvent(evt);

//alternative attempt

selector.dispatchEvent(new CustomEvent('ngModelChange') {
  detail: ["arg1"]
})

The problem arises as the argument being passed is an event type instead of string[], leading to errors within the code.

If anyone has insight on how to tackle this challenge or knows how to effectively test a selected value from a select element, your input would be greatly appreciated.

Answer №1

To make a comparison, you can verify the changes in the HTML code by updating [(ngModel)]="selectedRouters" and

(ngModelChange)="selectRouters(selectedRouters)"
as shown below:

<select [(ngModel)]="selectedRouters" name="routerName" class="form-control" id="routersSelect" size="12" (ngModelChange)="selectRouters(selectedRouters)" multiple>
    <option [value]="router.name" *ngFor="let router of routers$ | orderBy : 'name'">
        {{router.name}}
    </option>
</select>

Alternatively, you can follow the same approach within the HTML Page and modify the component code like this:

In HTML page

<select [ngModel]="selectedRouters" name="routerName" class="form-control" id="routersSelect" size="12" (ngModelChange)="selectRouters($event)" multiple>
    <option [value]="router.name" *ngFor="let router of routers$ | orderBy : 'name'">
        {{router.name}}
    </option>
</select>

In Component page

selectRouters(event) {
    this.routers$
        .filter(router => routers.includes(event.target.value.toString()))
        .forEach(router => router.setSelected(true))

    this.routers$
        .filter(router => !routers.includes(event.target.value.toString()))
        .forEach(router => router.setSelected(false))
}

Answer №2

For a solution to your issue, you may want to refer to the code snippet provided here. Hopefully this guide proves useful to you. Thank you for considering!

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

Detecting changes in an object property that is bound to another object property - a comprehensive guide

In my application, I am facing a challenge with displaying navigation items based on user rules. This is how I have tried to implement it: I define an object with the necessary rules: rules: { canSeeProfile: true, canSeeAdminZone: false, ... ...

angular-in-memory-web-api encounters a 404 error

I recently completed the heroes tour and now I am trying to work on something similar, but I seem to be having trouble understanding angular-in-memory-web-api. Here is a snippet of my code: clients-data.service.ts import { Injectable } from '@angular/ ...

Ionic 5.9.1 and Angular 12 FormControlName

Currently, I am delving into the realm of Reactive Forms with Angular 12 and Ionic 5.9.1 on my app. To my surprise, upon checking the latest documentation on the https://ionicframework.com/docs/api/input#properties Ionic website, I realized that there is n ...

The interface 'Response<ResBody>' has been incorrectly extended by the interface 'Response'

I am currently working with typescript and express in a node.js environment. Whenever I compile my code, I encounter the following bug: node_modules/@types/express-serve-static-core/index.d.ts:505:18 - error TS2430: Interface 'Response<ResBody>& ...

Showing information from a JSON dataset of users once a specific User ID has been chosen

My task involves displaying user data from an array and then showing the details of the selected user. I attempted to achieve this with the following code: users = USERS; // contains data selectedUser: User; constructor() { } ngOnInit() { } onSelect(i ...

What is the best way to prevent external scrolling when the mat-autocomplete panel is displayed?

When trying to open a mat-autocomplete in Angular Material, I noticed that the background content is still able to scroll. I attempted using the block strategy but it didn't have the desired effect. ...

Is there a way to access the value of a variable from a .ts file within a .scss file?

Utilizing a css-only pie chart, I am looking to incorporate the value of this.performance in my scss to determine the percentage. How can I manipulate my scss file from .ts file? Below is a snippet of my css code in scss: $configs: ( chart-one: ( sv ...

Using Typescript and React to assign an array object to state

Here is the situation: const [state, setState] = useState({ menuCatalog: true, menuCommon: true, fetched_data: [] }); An example of data I am trying to set to the state property "fetched_data" looks like this: [{"id": 1, "name": "some_name", " ...

Issue with Rxjs switchMap function not correctly executing the provided function

Currently utilizing the Subject observable provided by rxjs. In my component, I have implemented two methods. Search search(terms: Observable<string>) { return terms.pipe( debounceTime(400), distinctUntilChanged(), switchMap(term => ...

Sending data between Angular 4 components without using parent-child relationships

Current Scenario: In my project, there is a component that displays tiles, with each tile representing an item from an array. These items are looped over using ngFor. The requirement is that when a tile is clicked, the corresponding object should be passe ...

Integrating additional JavaScript into an Ionic 2 project

Imagine we have a foo.js file containing a variable, function, and class that are not yet part of the project. Now suppose we want to access these elements in our home.ts method or make them globally available for use within a home.ts method. How can this ...

Exploring Appsetting Configuration in AppModule of Angular 8

I'm looking to update my configuration in the appsettings file by replacing a hardcoded string with a reference to the appsetting. Currently, I have this hardcoded value in appmodule.ts: AgmCoreModule.forRoot({ apiKey: 'testtesttest', li ...

Is it possible that Angular2 is unable to properly establish the default value when it is selected?

I've been attempting to establish a default value for my selection by using [selected]= "selected_choice == 'one'" similar to this method but unfortunately, it didn't yield the desired result. Upon hearing that [selected] is no long ...

Ways to retrieve the initial 4 elements from an array or class organized by their price entries in ascending order

Let's say we have an array of objects representing products: Products: Product[] = [ { id: 1, name: 'Milk', price: '1' }, { id: 2, name: 'Flour', price: '20' }, { id: 3, name: 'Jeans', pri ...

How can I implement a bootbox alert in Typescript/Angular2?

Trying to incorporate Bootbox into my Angular2 project has proven to be a challenge. Despite extensive searching, I have been unable to find a satisfactory solution. I experimented with using angular2-modal as an alternative, but encountered numerous ...

Having issues with my Angular 4 + MVC web application not functioning properly in Internet Explorer

After creating an application using Angular 4 and MVC, I noticed a problem specifically with Internet Explorer. The application runs smoothly on Chrome, Firefox, and other browsers except for IE. Does anyone have any suggestions on how to resolve this br ...

Angular 10 - Timezone Detection and Interactive Calendar

I am encountering a major issue with the Angular DateTimePicker and TimeZone functionality. I need to dynamically switch the TimeZone at runtime in my component. Every date displayed on the frontend must be converted, while every date sent to the backend n ...

Validate prop must consist of one of two functional components

I am looking to ensure that a prop can only be one of two different components. Here is what I currently have: MyComponent.propTypes { propA: PropTypes.oneOfType([ PropTypes.instanceOf(ClassComponentA) PropTypes.instanceOf(ClassCompon ...

What is the correct way to write an asynchronous Express middleware function in Typescript?

Can anyone help me figure out how to correctly define a return value for an express middleware that utilizes async/await? I've been experimenting with different approaches but haven't found success yet. Additionally, I'm attempting to exten ...

I am having trouble getting Angular 6 to work with lowdb

I am currently in the process of developing an Electron app with Angular 6, utilizing lowdb as a local database. This is all very new to me and I am learning through trial and error. However, I seem to be encountering difficulty resolving the following er ...