我有一个子组件如下,
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();
}
}
我在父组件中使用此子组件,如下所示,
<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>
当更改下拉列值设置正确时,单击清除过滤器时我将重置值。但是值的变化没有反映在父组件上。它仍然显示选定的值。 这是清除所选值的功能。
clearFilters() {
this.selectedRegion = '';
}
问题是什么?
答案 0 :(得分:2)
您没有更新selectedItemName
使用此代替@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;
}
}