The function onSelectChange will output the first item of the list to the mdOption without fail

Currently, I am utilizing Angular Material within Angular 4 (version 4.3.4) and have encountered an issue with the selection event. Specifically, I am attempting to clear the input and then store the selected object in a separate list upon selection. Strangely, the onSelectChange output consistently passes the first item as the parameter. Any insights on what might be causing this behavior?

Below is my template setup:

<md-autocomplete [displayWith]="displayRole" #auto="mdAutocomplete">
    <md-option 
        *ngFor="let role of roles | acrole: roleField.value | slice:0:4; let i=index;" 
        [value]="role"
        (onSelectionChange)="AddRole(role)" >
        <div class="label">
          {{role.label}}
        </div>
    </md-option>                    
</md-autocomplete>

Furthermore, here is the function AddRole that I am using:

AddRole(role: Role)
{  
   // Interestingly, role always ends up being the initial role in the list regardless of which option is clicked.
   this.selectedList.push(role) 
}

Answer №1

Utilizing the onSelectionChange event allows for distinguishing between when an item is selected or unselected. To differentiate between the two cases, you must include an $event parameter in the target method.

Below are the modifications required to ensure that your changes function as intended:

In your component html:

<md-autocomplete [displayWith]="displayRole" #auto="mdAutocomplete">
    <md-option 
        *ngFor="let role of roles | acrole: roleField.value | slice:0:4; let i=index;" 
        [value]="role" 
        (onSelectionChange)="AddRole($event, role)">

        <div class="label">
            {{role.label}}
        </div>
    </md-option>
</md-autocomplete>

... and in your component.ts, modify the method as follows:

AddRole(event: MdOptionSelectionChange, role: Role) {  
    if (event.source.selected) {
        this.selectedList.push(role);
    }
}

Here is a PLUNKER DEMO based on the Material documentation example. It would be beneficial for the documentation to provide clearer guidance on these adjustments.

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

Is it possible to retrieve a union type property as an array of values in order to conduct a flexible type validation process?

Currently, my code looks something like this: interface Apple { type: 'Apple' } interface Banana { type: 'Banana' } interface Coconut { type: 'Coconut' } type Fruit = Apple | Banana | Coconut type AppleOrBanana = App ...

How should one approach working with libraries that do not have type definitions in TypeScript?

My current situation involves working with libraries that are untyped and resulting in warnings. I am curious about the best approach to address this issue - should I adjust configurations, use tslint ignore on a line-by-line basis, or possibly create du ...

Utilizing Typescript to define key-value pairs within a structured form

I've been creating a form structure that's functioning smoothly, but I've encountered an interesting issue with field validation in the validation part. While my Visual Code is pointing out that 'required2' in the phone constant n ...

Tips for avoiding the influence of the parent div's opacity on child divs within a Primeng Carousel

I'm struggling to find a solution to stop the "opacity" effect of the parent container from affecting the child containers. In my code, I want the opacity not to impact the buttons within the elements. I have tried using "radial-gradient" for multipl ...

Preventing a page refresh in Angular 2 on an ASPX page: Strategies for success

The use of the pagemethod is successful, but I encountered an issue with the webmethod causing the page to refresh, which defeats the purpose of using Angular 2. Is there a way to prevent the form from refreshing the page? index.aspx <body> &l ...

Incorporating Paypal subscription functionality and refining subscription challenges

The angular project I'm working on requires configuring a PayPal payment gateway for create subscription, cancel subscription, and upgrade subscription functionalities. I have encountered two issues with PayPal: 1) The PayPal button has been success ...

Tips for retrieving information from a Vuetify modal window

Is it possible to retrieve data from a dialog in the VueJS Vuetify framework? Specifically, how can I access the username or password entered in the NewUserPopup.vue dialog from app.vue? App.vue = main template NewUserPopup.vue = Dialog template imported ...

inject a dynamic loading icon within the choices of a datalist in an Angular application

<input list="dataUsers" formControlName="user" placeholder="Type the user name" class="form-control form-control-lg" type="text" (ngModelChange)="doSearch($event)"/> <datalist id=&q ...

Utilize an external JavaScript function within a React and TypeScript document

I have encountered an issue in my React/Next.js/TypeScript file where I am trying to load the YouTube iframe API in my useEffect hook. Here is the code snippet: useEffect(() => { const tag = document.createElement('script'); tag.src = ...

Tips for injecting Angular service for login in Cypress tests

Recently, I decided to incorporate Cypress into my testing process for my Angular application. Following Cypress's recommendation, I aimed to streamline testing by skipping the login screen and directly accessing my Angular LoginService. To guide me ...

Can anyone suggest a simpler method for creating function signatures with multiple conditions?

In my function, the first argument now determines if the function should receive an array or not. This function is similar to Foo type stringF = (arr: false, type: 'str', value: string) => void type numberF = (arr, false, type: 'num&apo ...

Create a new instance of the parent class in TypeScript to achieve class inheritance

Looking for a solution to extending a base class Collection in JavaScript/TypeScript to handle domain-specific use cases by implementing a "destructing" method like filter that returns a new instance with filtered elements. In PHP, you can achieve this usi ...

Encountering an issue with applying D3 fill to a horizontal stacked bar chart in Angular using TypeScript. When using .attr("fill", ..) in VSC, an error stating "No overload matches this call" is displayed

My goal is to create a stacked horizontal bar chart in d3, and I've been following the code example provided here. To showcase my progress so far, I have set up a minimal reproduction on stackBlitz which can be found here. While there are no errors ...

Tips for implementing an 'exclude' feature in TypeScript without encountering any error notifications

export function omit<T, U extends keyof T>(obj: T, keys: U[]): Omit<T, U> { return Object.keys(obj).reduce( (acc, curr) => (keys.includes(curr as U) ? acc : { ...acc, [curr]: obj[curr] }), {} ) as Omit<T, U>; } Encounter ...

CDK Drag and Drop capability for lists within lists

I am trying to figure out how to display users and their corresponding information in a structured way. Each user should be presented in their own column, with the associated information displayed within that column. I have been attempting to drag and drop ...

Exploring Cypress component testing by intercepting getServerSideProps requests

I'm struggling to find a way to intercept the getServerSideProps when using cypress component testing. After extensive research, I found some useful resources: Link 1 Link 2 Link 3 Link 4 If you're interested, you can also check out this ex ...

Issue detected in the ngx-joyride package: Error found in ./node_modules/ngx-joyride/assets/images/close.svg

During my build process, I encountered an error with ngx-joyride: ERROR in ./node_modules/ngx-joyride/assets/images/close.svg Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type." <line x1="1" y1=" ...

The value I'm receiving for my list of objects is not accurate

Currently, I'm experimenting with implementing TYPEHEAD for user input using the ng-bootstrap library. The goal is to display a list of objects (similar to a select option without a dropdown box): HTML <input type="search" #instance="ngbTy ...

Creating a secure connection on localhost with angular dart webdev: A step-by-step guide

Currently, I am developing a web application using Angular Dart. One issue I encountered is accessing the user's location feature through geolocation, as browsers like Chrome require HTTPS for this functionality. When deploying the web application, th ...

Is there a way to alter the stroke color of an SVG icon in Angular 2 or 4 by clicking on it?

Having trouble with this code, can someone provide a solution? This is the SVG icon code: <svg id="Home" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52.28 43.49"> <defs> <style> .cls-1{fill:none;stro ...