Obtain the initial value and update the information without having to refresh the page using Angular Select

One issue I am facing is to retrieve the default value in the select dropdown

Another problem arises when I select an option from the first dropdown menu, the data appears in the second dropdown. However, upon changing the selection in the first dropdown again, the data disappears and requires a reload to reappear.

Here is my HTML code:

 <div class="form-group">
          <label for="Morceau">Artiste <span style="color: red;">*</span> </label>
          <select #mySelect (change)="onMakeChange( mySelect.value)" [(ngModel)]="suggestion.artiste_id"
            name="artiste_id" type="text" class="form-control  z-depth-1" id="Morceau" style=" border-style: solid;
              border-width: 3px; border-color:#000">
            <option value=""></option>
            <option *ngFor="let artiste of artistes" value="{{artiste?._id}}">{{artiste?.artiste_name}}</option>
          </select>
        </div>
        <div class="form-group ">
          <label for="Artiste">Morceau <span style="color: red;">*</span> </label>
          <select type="text" class="form-control  z-depth-1" id="Artiste" style=" border-style: solid;
              border-width: 3px; border-color:#000" [(ngModel)]="suggestion.lyrics_id" name="lyrics_id">
            <option value=""></option>
            <option *ngFor="let lyrics of lyrics" value="{{lyrics?._id}}">{{lyrics?.titleOfLyrics}}</option>
          </select>
        </div>

**my TypeScript code is :**

 artistes: any[] = [];
  lyrics: any[] = [];
  suggestion: any = {
    artiste_id: "",
    lyrics_id: "",
    email: "",
    punchline: "",
  };
getAllArtiste() {
    this.artisteSRV.getAll().subscribe((data: any) => {
      this.artistes = data;
      console.log("artistes", data);
    });
  }
  getAllLyrics() {
    this.lyricsSRV.getAll().subscribe((data: any) => {
      this.lyrics = data;
      console.log("lyrics", data);
    });
  }
  onMakeChange($event) {
    if (this.suggestion.artiste_id)
      var selectedLyrics = this.lyrics.filter(
        (art) => art.artiste._id == this.suggestion.artiste_id
      );
    this.lyrics = selectedLyrics;
    delete this.suggestion.lyrics_id;
  }

Answer №1

this.lyrics was initially set to contain all the lyrics in your full list.

With this line:

this.lyrics = selectedLyrics;

You are now assigning a filtered set of lyrics to your original list of all lyrics.

So, when the user selects another artist,

var selectedLyrics = this.lyrics.filter(...)

You are filtering an already filtered list.

To address this issue, you should maintain two separate variables:

  • One for the complete list of lyrics which will always include all the lyrics before any filter is applied.
  • Another variable for the filtered list that is linked to the drop-down selection.

Here's a sample code snippet:

export class MyComponent {
  artists: Artist[] = [];
  lyrics: Lyrics[] = [];
  suggestion: any = {
        artist_id: '',
        lyric_id: '',
        email: '',
        punchline: ''
  };
  unfilteredLyrics: Lyrics[] = []; // <-- ADDED THIS

  constructor() {
    this.getAllArtists();
    this.getAllLyrics();
  }

  getAllArtists() {
    this.artService_getAll().subscribe((data: any) => {
      this.artists = data;
      console.log('artists', data);
    });
  }
  getAllLyrics() {
    this.lyricService_getAll().subscribe((data: any) => {
      this.unfilteredLyrics = data; // <-- ADDED THIS
      this.lyrics = data;
      console.log('lyrics', data);
    });
  }
  onSelectionChange($event) {
    if (this.suggestion.artist_id)
      var selectedLyrics = this.unfilteredLyrics.filter(
        art => art.artist._id == this.suggestion.artist_id
      );
    this.lyrics = selectedLyrics;
    delete this.suggestion.lyric_id;
  }
}

You can view the live example on StackBlitz here: https://stackblitz.com/edit/angular-posts-behavior-subject-procedural-vs-declarative-eoqqcx

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

Utilizing Threejs to Unproject Vector3 from Camera

I'm currently working on a project using three-js where I am attempting to project 2D coordinates onto a sphere within the virtual world. The code snippet below functions perfectly when bound to the mousedown event: function project(point){ var x ...

Converting React Router Function into Typescript: A Step-by-Step Guide

Working on a React project that utilizes react-router-dom and the client requires converting the code to TypeScript. I created 2 folders: "RouteWrapper.js" and "ProviderRoutes.js" 1- "RouteWrapper.js" import React from 'react'; import PropTypes ...

A guide to verifying the type of response from an HTTP request in Typescript

Issue: I am currently working with Firebase cloud functions and encountering a specific problem. Let's consider the following function: function giveMeAnInteger(): number { return 123; } When calling this function like so: function call() { ...

Tips for concealing the angular component depending on a specific circumstance

I have developed a custom directive for validating input. It is designed to check the length of the input. If the length is zero, an error message will be displayed. However, I am facing difficulty in hiding the error message when the input is filled with ...

Encountering "Error: Class constructor vA cannot be invoked without 'new'" when using Angular 10 Kendo Grid

I am currently working on integrating a Kendo Grid into my Angular application. However, I have run into an error when enabling the Kendo Grid component: vendor.4add67dadae0cd9152b9.js:16 ERROR Error: Uncaught (in promise): TypeError: Class constructor vA ...

An error is being encountered with web-animations-js on IE 9, showing the following message: "SCRIPT5007: Object expected; web-animations.min.js (15

Currently, I am utilizing Angular 5. Below are the steps I followed: Firstly, added web-animations-js as a dependency : npm install web-animations-js Then, uncommented the following line in polyfils.ts import 'web-animations-js'; // Run npm ...

What steps should I take to handle JSON data in my component's state if it's causing issues when I try to access the data within a variable

I am facing an issue where I am trying to extract data from my state and then integrate it into the config variable in order to display this data on highCharts. However, I keep encountering errors such as "Cannot read property 'SeriesDates' of un ...

Struggling to figure out why jqueryrotate isn't functioning as expected

I'm having trouble getting example #2 of jqueryrotate from this page to work on a simple HTML page. Can someone help me figure out what I'm doing wrong? Thanks! Here is the code I'm using: <!DOCTYPE html> <head> <script typ ...

How to align icon and text perfectly in a Bootstrap 5 Button

I am looking to align icons and text within a modal body: <div class="modal-body"> <div class="d-grid gap-2" id="someButtons"> </div> </div> This code snippet demonstrates how I insert buttons ...

A valid ReactComponent must be returned in order to properly render in React. Avoid returning undefined, an array, or any other invalid object

While working on my react application, I came across an error that I have been trying to troubleshoot without any success. It seems like I must be overlooking something important that could be quite obvious. *Error: VideoDetail.render(): A valid ReactComp ...

Two controllers rely on an HTTP request within a factory for their functionality

I am facing a situation where I have 2 controllers that rely on data fetched by a function within a factory. The structure of my factory is like this: factory.getData = function() { const req = {...}; return $http(req).then((res) => { this ...

jquery mobile popup message will fade away within a short time interval

In my main page, I have the following code: $(document).bind("pageinit", function () { $.mobile.loading('hide'); }); I am displaying a popup message using the following code: $.mobile.loading('show&apos ...

Tips for implementing autocomplete with tags in Jquery

I have a drop-down with autocomplete functionality, and I am attempting to add tags to the list. When I populate the availableTags array and run the project, everything works fine. File.JS var availableTags = []; $(document).ready(function(){ $(function() ...

Here is a unique rewrite of the text:"Implementing a feature to upload an image in PHP and AJAX without

Although it may seem repetitive, I have yet to find a solution that perfectly fits my requirements. I am looking to upload an image to a designated folder by simply selecting a file in the file browser, without the use of a submit button (which I have acco ...

The button will continue to be enabled even if the textfield is empty

I have a task to implement a feature on a webpage where the submit button should remain disabled until all values are entered in the textbox. However, I am facing an issue where the submit button is already active when the page loads. .directive('pas ...

Managing data from two tables in Node.js with ejs

I have a question regarding my node.js project that I need help with. As a beginner in this field, I believe the answer may be simpler than anticipated. In my code file named index.js, I found the following snippet after referring to some online documenta ...

Why are static PropTypes used in ReactJS and do they offer any solutions or are they merely a recurring design choice?

While delving into the code base of a web application, I came across some static PropTypes that left me questioning their purpose and necessity. Here is a snippet of the code in question: static propTypes = { fetchCricketFantasyPlayers: PropTypes.fun ...

What is the best way to assign default values when destructuring interfaces within interfaces in TypeScript?

My goal here is to create a function that can be used with or without arguments. If arguments are provided, it should work with those values; if not, default values should be used. The issue I'm facing is that although there are no TypeScript errors ...

Is the data set in stone, or is it just the API data that can

Recently, I embarked on the journey of creating a blog using nextjs, MongoDB, and express. Taking advantage of getStaticProps and getStaticPaths, I was able to dynamically generate pages for each blog post and display them individually. However, I encoun ...

Angular2 - Easily update form fields with just a click

I have a form that retrieves data from a service and presents it in the following format: @Component({ selector: 'profile', template: `<h1>Profile Page</h1> <form [ngFormModel]="myForm" (ngSubmit)="onSubmit()" #f="ngFor ...