Component remains populated even after values have been reset

My child component is structured as shown below,

ChildComponent.html

<div>
    <button type="button" data-toggle="dropdown" aria-haspopup="true" (click)="toggleDropdown()">
        {{ selectedItemName }} <span></span>
    </button>
    <div *ngIf="showDropdown">
        <ul class="default-dropdown">
            <li *ngFor="let item of list" (click)="onSelectItem(item.value)" [ngClass]="{'active': item.value==selected}">
                <a>{{item.name}}</a>
            </li>
        </ul>
    </div>
</div>

ChildComponent.ts

import { Component, Input, Output, EventEmitter } from '@angular/core';
declare const _: any;
@Component({
  moduleId: module.id,
  selector: 'child-component',
  templateUrl: 'child.component.html'
})
export class ChildComponent {
  @Input() list: any;
  @Input() selected: string;
  @Output() onSelect = new EventEmitter<any>();
  showDropdown: boolean;
  selectedItemName: string;
  
  constructor() {
    this.showDropdown = false;
  }
  
  ngOnInit() {
    this.setSelected(this.selected);
  }
  
  setSelected(selected: string) {
    const selectedItem = _.find(this.list, (item: any) => {
      return item.value === selected;
    });
    this.selectedItemName = selectedItem.name;
  }
  
  toggleDropdown() {
    this.showDropdown = !this.showDropdown;
  }
  
  onSelectItem(selected: string) {
    this.onSelect.emit(selected);
    this.setSelected(selected);
    this.toggleDropdown();
  }
}

I am including this child component in the parent component like this,

<div class="col-md-offset-2 col-md-8 search-filter-buttongroup-wrapper">
    <ul>
        <li class="timeframe">
            <child-component [list]="allRegions" [selected]="selectedRegion" (onSelect)="onSelectRegion($event)"></child-component>
        </li> 
        <li class="clear-text header-search-block-text" (click)="clearFilters()">
            <span><img src="../imgs/reset.svg">Clear Filters</span>
        </li>
    </ul>
</div>

Although the dropdown values are being set correctly when changed, upon clicking "Clear Filters," the values do not reset on the parent component. The selected values remain unchanged. This is the method to clear the selected values.

clearFilters() {    
    this.selectedRegion = '';
}

What could be causing this issue?

Answer №1

Make sure to not forget to update the variable selectedItemName try using this code instead of @Input()selected:string:

  selected:string;
  @Input("selected") 
  set _selected(selected: string){
    this.selected = selected;
    if(this.list){
      const selectedItem = _.find(this.list, (item: any) => {
        return item.value === selected;
      });
      this.slectedItemName = selectedItem.name;
    }
  }

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

Issue: Unable to locate the module 'nexmo' & error TS2307: 'nexmo' module not found

Currently, I am utilizing the powerful NestJs Framework alongside typescript. My task involves incorporating two-factor authentication (SMS) using the Nexmo node library. You can find further information on their website: During the development phase, ev ...

Inferring types in a generic function with multiple parameters

In my attempt to configure a generic with the parameter serving as the key of another object, I have found success using extends keyof when both types are provided as parameters to the function. However, I encountered an issue when the type that provides ...

What is the process for adjusting the color of axes in vue-chartjs?

Seeking help on how to adjust the color of the axis in my graph. Has anyone encountered a similar issue before? The chart I'm working with resembles the one shown in the image. Not sure if this issue is related to it being a time graph. Below is the V ...

Dealing with incorrect type declarations in Typescript when using Material-UI Higher Order Components can

Currently, I am in the process of upgrading from Material-UI 1.x to the newer version Material-UI 3.9.2. I had several components that were functioning well with Higher Order Components (HOC), but when it comes to migrating them to 3.9.2, I am facing some ...

What Causes CORS Errors When Sending Encoded Information?

Dealing with poor data quality is a challenge I face. An example of this is when the primary key value of a table contains spaces and special characters, like 35581/H0034-100003 My goal is to retrieve a record by its primary key value using a GET request ...

Unlocking the potential of the ‘Rx Observable’ in Angular 2 to effectively tackle double click issues

let button = document.querySelector('.mbtn'); let lab = document.querySelector('.mlab'); let clickStream = Observable.fromEvent(button,'click'); let doubleClickStream = clickStream .buffer(()=> clickStream.thrott ...

The WebSocket connection in the browser, when accessed through a remote server, typically shows a CLOSED state in the readyState property during the on

Local server operations are running smoothly. However, when testing on a remote server with Nginx, the issue arises where the readyState inside the event handler onopen is consistently showing as CLOSED. Nginx configuration: server { server_name doma ...

Encountering the message "npm ERR! missing script: start" following the update to .Net 3.0

Previously, the ASP.Net Core 2.2 code (upgraded from 2.1) did not include a start script in package.json. https://github.com/TrilonIO/aspnetcore-angular-universal/blob/master/package.json Upon upgrading to ASP.Net Core 3.0, it now requires a start script ...

The soft keyboard on Android devices may be obscured by an input field when using Cordova

When I use the text input field on my Android phone, the soft keyboard covers the input field. My app is built with Cordova and Angular 6. I have attempted the following solution: <preference name="Fullscreen" value="false" /> <edit-config file ...

Leveraging TypeScript's declaration file

Greetings! I am currently facing an issue while utilizing a declaration file in my TypeScript project. Here is the declaration file that I am working with: // Type definitions for Dropzone 4.3.0 // Project: http://www.dropzonejs.com/ // Definitions ...

What is the process for linking read-only methods to Redux object instances?

Let's say I have a "user" object stored in redux, with fields for first name and last name (interface User { firstName : string, lastName : string} if using typescript). After retrieving a user from redux, I want to obtain the full name of the user by ...

Adding HTML elements to Material 2 Snack bar: A step-by-step guide

I am in need of displaying a spinner inside Material 2 Snack bar. Within our application, we utilize Snack bar to showcase loading, success, and error messages. For the loading message specifically, I would like to include a spinner as well. However, my a ...

Why do my messages from BehaviorSubject get duplicated every time a new message is received?

Currently, I am using BehaviorSubject to receive data and also utilizing websockets, although the websocket functionality is not relevant at this moment. The main issue I am facing is why I keep receiving duplicated messages from BehaviorSubject. When exa ...

Angular directive for converting fields to title case

I have created a custom directive to transform all table column data into titlecase. The directive I implemented is designed to achieve this transformation, keeping in mind that pipes are not being counted: @Directive({ selector: '[appTitleCase]' ...

Add a class individually for each element when the mouse enters the event

How can I apply the (.fill) class to each child element when hovering over them individually? I tried writing this code in TypeScript and added a mouseenter event, but upon opening the file, the .fill class is already applied to all elements. Why is this ...

Error occurs in Typescript when attempting to store data in a record using a pointer

When working with nodes and organizing them into a tree structure, I encounter an issue: This is the definition of the interface: interface IDataObj { children: IDataObj[], frontmatter : { type: string, title: string, path: string}, name: str ...

How to Incorporate and Utilize Untyped Leaflet JavaScript Plugin with TypeScript 2 in Angular 2 Application

I have successfully integrated the LeafletJS library into my Angular 2 application by including the type definition (leaflet.d.ts) and the leaflet node module. However, I am facing an issue while trying to import a plugin for the Leaflet library called "le ...

Who is responsible for ensuring that the data has been successfully stored in the state?

As I work on utilizing SSR with TransferState, a question arises about the assurance of data storage in the transferState. This concern stems from the asynchronous nature of http.get, which may result in content delivery to the client before the desired ...

Using Angular components to manipulate the CSS in the DOM

Struggling with dom manipulation in an angular/node.js environment using typescript for my visualcomponent.html The second inline styling works fine, showing the h1 in blue color. However, I run into issues when trying to embed strings within the innerHTM ...

Using [file_id] as a dynamic parameter in nextjs pages

I am working with a nextjs-ts code in the pages/[file_id].tsx file. import Head from 'next/head'; import Script from 'next/script'; import Image from 'next/image'; import Link from 'next/link'; import { NextApiReques ...