Enhance user experience with Angular Material and TypeScript by implementing an auto-complete feature that allows

Currently facing an issue with my code where creating a new chip triggers the label model to generate a name and ID.

The problem arises when trying to select an option from the dropdown menu. Instead of returning the label name, it returns an Object.

The UI snapshot reveals that the md-autocomplete dropdown displays the name correctly. However, upon selecting an option like hotel, it returns {"id":1,"name":"hotel"}.

I need help in modifying the code to return only the name without the associated object.

UI:

https://i.sstatic.net/gMLjs.png

labels.html:

<md-content layout="column">
    <md-chips ng-model="cont.vm.selectedLabels" md-autocomplete-snap md-require-match="false" 
        md-on-append="cont.createLabel($chip)">
      <md-autocomplete
          md-selected-item="cont.vm.selectedItem"
          md-search-text="searchText"
          md-items="item in cont.querySearch(searchText)"
          md-item-text="item.name"
          md-min-length="2"
          placeholder="Type to add a label">
        <span md-highlight-text="cont.vm.searchText" >{{item.name}}</span>
           <md-not-found>
             No matches found.
            </md-not-found>       
      </md-autocomplete>
      <md-chip-template>
        <span>
          <strong>{{$chip.name}}</strong>
        </span>
      </md-chip-template>   
    </md-chips>
    <br />
    <p class="md-title">Existing Labels</p>
    <md-list>
      <md-list-item class="md-2-line label-option" ng-repeat="label in cont.vm.labels" layout="row"
          layout-wrap>
        <div class="md-item-text md-whiteframe-z1" flex>
          <h3>(NAME: {{label.name}}) (ID: {{label.id}})</h3>
        </div>
      </md-list-item>
    </md-list>
</md-content>

labelsController.ts:

constructor(private $scope: common.IScope<LabelScope>, 
                private labelsService: ILabelsService){

                    super($scope);
                    this.vm.labels = this.loadLabels();
                    this.vm.selectedLabels = [];
                    this.vm.selectedItem = null;
                    this.vm.searchText = null;         
                    console.log($scope);           
            } 

            private loadLabels() {
                return this.labelsService.getLabels();
            }
            // Returns list of labels that already exists
            public querySearch (query: string) {
                var results = query ? this.loadLabels() : [];
                return results;
                console.log(results);
            }          
            // Returns name + ID on new chip created
            public createLabel($chip: string) {
                return {
                    name: $chip,
                    id: 4
                };                                               
            }

labelsService.ts:

 private mockLabels: Array<Label> = [
            new Label(1, 'hotel'),
            new Label(2, 'sport'),
            new Label(3, 'gaming'),
            new Label(4, 'apple'),
            new Label(5, 'retail')
        ];

        public getLabels() {
            return this.mockLabels;   
            console.log(this.mockLabels);         
        }

Answer №1

A similar issue arose for me some time back. The root cause lies in the fact that the md-on-append function gets triggered even when an item is selected from the dropdown menu.

Upon selection, the following data structure is returned:

{
    name:{
           name:hotel,
           id:1
    },
    id:4
}

To address this, it's necessary to make adjustments to the code within the createLabel() function.

JavaScript Code snippet:

public createLabel($chip) {
    angular.forEach(this.vm.selectedLabels,function(element,index){
         if(element.name==$chip.name||element.name==$chip){
             this.vm.selectedLabels.splice(index,1);
         }
    })
    if($chip.id==undefined){
         return {
           name: $chip,
           id: 4
         };                                 
    }
    else{
        return $chip;
    }

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

What sets Protractor apart from Grunt?

According to the Protractor website (http://www.protractortest.org/#/infrastructure), Protractor utilizes Selenium for browser automation. However, when browsing through the Grunt website (http://gruntjs.com/), it's mentioned that Grunt is also used f ...

Utilizing various AngularJS filters with multiple input sources

Looking to enhance my user array filtering process with two input boxes. Here's how the array is structured: $scope.users = [{ id: 1, fname: 'Sophia', lname: 'Smith', email: '<a href="/cdn-cgi/l/email ...

AFrame: keeping an element's world position and rotation intact while reparenting

I am attempting to reassign a child element (entity) to another parent while preserving its position, rotation, and possibly size in the scene. Ideally, I would like to implement a component (let's call it "reparent") that can be added to an entity to ...

How Can You Change the Position of a Threejs Vector3?

I'm attempting to create bones and then manipulate the vertices of each bone, but I am struggling with the correct syntax. Here is an example of what I have tried: var v = new THREE.Vector3(0,0,0); var b = new THREE.Bone(); b.position.x = 5; b.positi ...

Enhance the functionality of a module by incorporating plugins when Typescript definitions are divided into multiple files

During my exploration of Typescript 2.2, I encountered a challenge in defining a module for HapiJS with various plugin options. To streamline the core code, I split it into multiple .d.ts files and then imported and re-exported them all from the index.d.t ...

Determine the TR id when a button within a TD element is clicked using JavaScript/jQuery

Currently seeking a method to generate a unique identifier for use as a parameter in a JavaScript function. Specifically interested in extracting the id of the first td element if feasible. <tr id='it'><td id="#nameiron">Jason</td ...

Transform Image on Hover in ReactJS

I am working on a Card Component that includes an image and text. Initially, the image is redImage and the text is black. When hovering over the card, I want the redimage to change to whiteimage and the text color to change to white as well. The content ...

Arranging elements in a list according to their position on the canvas using AngularJS

I am currently working on drawing rectangles on an html5 canvas using the JSON format provided below. My goal is to sort the array based on the x and y locations of each element. { "obj0": { "outerRects": [ { "outerRectRoi": { "x1": 0, " ...

What is the process for saving an image from a Three.js canvas?

Can you provide tips on saving an image from a Three.js canvas? I'm having trouble making Canvas2Image work with Threejs. The issue seems to arise because the canvas object needs a div to be attached to before it is defined. Check out this resource ...

What causes getBoundingClientRect() in Javascript to occasionally produce decimal values?

Currently, I am experimenting with an HTML5 canvas element. A major concern of mine is setting up a mousemove event to monitor the movement of the mouse over the canvas for drawing and other purposes. Unfortunately, I have not been able to locate a definit ...

Troubleshooting the issue with reactdom.render() functionality in CodeSandbox

Having issues with ReactDom in CodeSandbox for React. The HTML file includes: <body> <div id="root"></div> </body> <script src="scr/index.js"> The JavaScript file (named index) includes: ReactDOM.rende ...

The function Sequelize.create() does not exist

My attempts to push my DB with sequelize are not working, even though I have set up this schema for the DB: module.exports = (sequelize, DataTypes) => { const Problems = sequelize.define("Posts", { theme: { type: DataTypes.ST ...

Is there a way to store session variables in Angular without the need to make an API call?

I am currently working with a backend in PHP Laravel 5.4, and I am looking for a way to access my session variables in my Angular/Ionic project similar to how I do it in my Blade files using $_SESSION['variable_name']. So far, I have not discove ...

Is there a simple method to submit to a URL without relying on ajax?

When it comes to using jQuery, the $.ajax() function is typically used for POST requests to a URL. However, in my particular situation, I am unable to use this function. I need the client to send a POST request to a URL and have the server redirect the use ...

Utilize decorators for enhancing interface properties with metadata information

Can decorators be utilized to add custom information to specific properties within an interface? An example can help clarify this: Interface for App state: export interface AppState { @persist userData: UserData, @persist selectedCompany: UserCo ...

Is it possible to modify the inactive color of just one radio button in Framework7?

Is there a way to change the inactive color of only one radio button in Framework7? I am aware that using the CSS variable --f7-radio-inactive-color allows me to set the inactive color for all radio buttons. However, I specifically want to modify the inac ...

Invoking a function in an Angular 4 component using a <td> element

Take a look at this block of code: personListComponent.html <tr *ngFor="let person of personService.getPersons()"> <td (onShow)="getCountry(person)">{{person.name}}</td> <td>{{country}} </tr personListComponent.ts ...

SyntaxError: Encountered an unexpected token that is not jsonp, could it be trying to parse json instead?

As a newcomer to AJAX and Javascript, I am attempting to integrate them with an API following this structure: http://localhost:8088/JobPositionForDd: { "data": [{ "_id": "529dc2dfd0bf07a41b000048", "name": "Junior Android" }, { ...

I'm having trouble viewing the unique Google Map design on my application

I have recently customized Google maps following the guidelines in this documentation: https://developers.google.com/maps/documentation/javascript/styling For styling, I utilized the Cloud tool and opted for the available template instead of using JSON st ...

Angular - Leveraging Jest and NgMocks to Mock Wrapper Components

Within our project, we have implemented a feature where user roles can be assigned to various elements in the application. These roles determine whether certain elements should be disabled or not. However, due to additional conditions that may also disable ...