我正在做Angular项目。
当用户点击某个类别时,我需要显示相应的子类别。
例如,单击Drinks I need to display:Coke,Fanta,Pepsi...
例如,通过单击“食物”,我需要显示:“Burgers”、“Potatoes”、“Fish”。
当我点击main groups时,这是有效的,子组正在改变,并按预期显示。
但我想将饮料设置为默认类别,所以当我进入屏幕时,我希望看到百事可乐饮料和可口可乐,,百事可乐。就像我手动按下饮料一样..
我试着在next way上实现这一点:
第1步:
从数据库获取数据,所有主类别,所有子类别,所以我可能会应用过滤器-基于categoryId -获取所有子类别:
export class MainScreenCategories implements OnInit {
@Input() groups: Group[];
@Input() subGroups: Group[];
filteredSubGroups: Group[];
selectedId: string;
selectedSubId: string;
constructor(
private _ref: ChangeDetectorRef,
private _activatedRoute: ActivatedRoute,
private _groupService: GroupService,
private _http: HttpClient,
private _articleService: ArticleService,
private _globalHelper: GlobalHelperService
) { }
ngOnInit() {
this.selectedId = '78ebcad8-8cb0-4172-8cd8-bb6fb6b3bf53';
this.groups = this._activatedRoute.snapshot.data['groups'];
this.subGroups = this._activatedRoute.snapshot.data['subGroups'];
// This is source to my template directive *ngFor - filteredSubGroups
this.filteredSubGroups = this.subGroups.filter(item => item.parentId == this.selectedId);
console.log(this.filteredSubGroups);
//this._ref.detectChanges();
//I've tried adding timeout while fetching data
//this._groupService.getAll().subscribe(data => setTimeout(() => this.groups = data, 0));
//this._groupService.getAllSubGroups().subscribe(data => setTimeout(() => this.subGroups = data, 0));
}
第2步:
编写一些HTML来显示数据:
<div class="tab-pane" id="whatever">
<ul>
<li *ngFor="let subgroup of filteredSubGroups">
<button type="button" data-toggle="" data-target="" class="btn categories-btn">
{{subgroup.title | uppercase}}
</button>
</li>
</ul>
</div>
正如你所看到的,我循环filteredSubGroups
来显示子类别。
我在ngOnInit
中的console.log(filteredSubGroups)
也包含正确的数据,但当我第一次运行app时,我在控制台中收到以下消息:
当我清除控制台并转到另一个组件的模板,并返回到这个模板时,我可以在我的控制台中看到不再有错误,只有3个子类别记录在那里,因为我在ngOnInit
console.log(filteredSubGroups)
中说,
但是即使它们被记录了,它们在html模板中也是不可见的,这是最大的问题,我不知道为什么?
谢谢你们
任何一种帮助都是很棒的!
发布于 2018-06-26 07:14:37
也许你应该订阅激活的路由数据。使用像这样的东西。
this.route.data.subscribe((data) => {
if(data){
const {groups, subGroups} = data;
this.groups = groups;
this.subGroups = subGroups;
this.filteredSubGroups = this.subGroups.filter(item => item.parentId == this.selectedId);
}
})
可能发生的情况是,对路由的第一次调用会因为null而杀死组件。然后,在有时间异步获取数据后,单击鼠标会重新初始化组件。
https://stackoverflow.com/questions/51032667
复制相似问题