I have a child component as follows,
Child component.html
<div >
<button type="button" data-toggle="dropdown" aria-haspopup="true" (click)="toggleDropdown()">
{{ slectedItemName }} <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>
Child component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
declare const _: any;
@Component({
moduleId: module.id,
selector: 'dropdown',
templateUrl: 'dropdown.component.html'
})
export class DropdownComponent {
@Input() list: any;
@Input() selected: string;
@Output() onSelect = new EventEmitter<any>();
showDropdown: boolean;
slectedItemName: 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.slectedItemName = selectedItem.name;
}
toggleDropdown() {
this.showDropdown = !this.showDropdown;
}
onSelectItem(selected: string) {
this.onSelect.emit(selected);
this.setSelected(selected);
this.toggleDropdown();
}
}
I am using this child component in the parent component as follows,
<div class="col-md-offset-2 col-md-8 search-filter-buttongroup-wrapper">
<ul>
<li class="timeframe">
<dropdown [list]="allRegions" [selected]="selectedRegion" (onSelect)="onSelectRegion($event)">
</dropdown>
</li>
<li class="clear-text header-search-block-text" (click)="clearFilters()">
<span><img src="../imgs/reset.svg">Clear Filters</span>
</li>
</ul>
</div>
when changing the dropdown values are setting correctly, on clicking clear filters i am resetting the values. but the value changes are not getting reflected on the parent component. it still shows the selected values. this is the function to clear the selected values.
clearFilters() {
this.selectedRegion = '';
}
what is the issue?
You don't update selectedItemName
use this 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;
}
}