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

Unable to persist AWS CDK ec2.Instance userData configuration

Trying to launch an ec2 instance with AWS CDK has been successful, but I am struggling to make the userData persistent so it runs on every boot. Despite searching extensively, I couldn't find any documentation on how to achieve this. The code below wo ...

Are you struggling with perplexing TypeScript error messages caused by a hyphen in the package name?

After creating a JavaScript/TypeScript library, my goal is for it to function as: A global variable when called from either JavaScript or TypeScript Accessible via RequireJS when called from either JavaScript or TypeScript Complete unit test coverage Th ...

What is the correct version compatibility matrix for Expo, NPM, Node, React Native, and TypeScript?

Currently, I am in the process of setting up React Native with TypeScript. Here are the steps I followed: npx react-native init MyApp --template react-native-template-typescript I made sure to install TypeScript as well: npm install -g typescript ' ...

The error message "Property 'DecalGeometry' is not found in the type 'typeof "..node_modules/@types/three/index"'."

Within my Angular6 application, I am utilizing 'three.js' and 'three-decal-geometry'. Here is a snippet of the necessary imports: import * as THREE from 'three'; import * as OBJLoader from 'three-obj-loader'; import ...

Is it possible for changes made to an object in a child component to be reflected in the parent component

When passing an object to the child component using , how can we ensure that changes made to a specific property in the object within the child component are visible in the parent component? In my understanding, changes would not be reflected if we were p ...

What is the correct way to extract a value from a keyvalue pair?

When dealing with an object that returns boolean "issues", I specify it as a string. If the value is true, I aim to show a checkmark; if false, I want to display a cross. <ul *ngFor="let filtered of reposFiltered | keyvalue"> <li *ngIf=& ...

Why does the request body show as null even after passing body data in Prisma?

My application uses Prisma for database storage with MySQL. It is built using Next.js and TypeScript. I have set up the API and it is functioning properly. However, when I try to save data sent through the API, the `request.body` is null. Interestingly, wh ...

Utilize Angular's $state service within a configuration setting to automatically redirect to a specific state using an interceptor

I'm working with restangular and have set up an interceptor to handle 401 responses by redirecting to another state. The issue is that angular only allows the injection of providers, not services, in config. Is there a way to access the $state: ng.u ...

Tips for extracting specific JSON response data from an array in TypeScript

I have an array named ReservationResponse, which represents a successful response retrieved from an API call. The code snippet below demonstrates how it is fetched: const ReservationResponse = await this.service.getReservation(this.username.value); The st ...

"Enhance your development experience with the TypeScript definitions for the Vue 2 plugin

Currently, I am utilizing VSCode alongside TypeScript classes for developing Vue 2 components. You can check out more information at: vuejs/vue-class-component. Within my present project, I make use of plugins like vue-i18n for handling translations of la ...

Transform ECMAScript Observable / Zen Observable into RXJS Observable

I currently have an ECMAScript Observable that is compliant with specifications, specifically sourced from the wonka library. I am facing challenges in converting this type of observable to an rxjs 6 observable. It appears that this conversion was possibl ...

The evaluation of mongodb-memory-server is experiencing issues with either failing or timing out

While setting up mongodb-memory-server in my backend for testing purposes, I encountered some issues during test execution that require debugging. The problem arises when running a test that creates a MongoDB document within the service being tested, leadi ...

Issue with Typescript express application utilizing express-openid-connect wherein cookies are not being retained, resulting in an infinite loop of redirects

For a while now, I've been facing a block with no resolution in sight for this particular issue. Hopefully, someone out there can lend a hand. Background I have a TS express application running on Firebase functions. Additionally, I utilize a custom ...

Type definition for Vuex store functionality

Working on creating a versatile type to provide typing hints for mutations in Vuex. After reading an inspiring article on Vuex + TypeScript, I decided to develop something more generic. Here is what I came up with: export type MutationType<S, P, K exten ...

Looking for help with setting up Nodemailer and installing it via NPM

I am currently developing a mobile application using Ionic with Angular/Typescript, and I'm in need of a front-end solution to dynamically send emails in the background to a specific email address. I tried using emailjs, but it requires JavaScript whi ...

The Influence of Getter Performance in Angular Templates

As I delve into an existing Angular application, I've noticed a pattern where values used in templates across many components are actually properties that are being accessed through getters and setters without any additional logic: <input type="nu ...

Creating and accessing files within the `dist` folder in Angular 5: A comprehensive guide

After deploying my Angular 5 app to Cloud Foundry, a file named app-number-version is automatically generated in the dist folder with just the version number (e.g., "1.0.0"). My goal is to show this version number in the navigation bar of our app's H ...

Tips for maintaining the menu state following a refresh

Is there a way to save the menu state when pressing F5? I'm looking for a similar functionality as seen on the Binance website. For example, clicking on the Sell NFT's submenu and then refreshing the page with F5 should maintain the menu state on ...

Contact creation not working on non-HubSpot form popups

I'm currently experiencing an issue with my website that has non-Hubspot forms. We have successfully integrated the tracking code to generate cookies for users, track their sessions, and enable the non-Hubspot forms. However, we are facing a problem s ...

Utilize global variables in ng-apimock mocks without the need for double quotes

We integrated ng-apimock into our Angular project and successfully created mock definitions and wrote tests using protractor. Now we are looking to implement global variables in our mock definitions. Here is an example of a mock definition: { "expressi ...