angular7 - applying *ngFor on
问题描述
To show data obtained from Api, I applied *ngFor directive on li tag. Then, I used interpolation to show the data inside the li tag. But I am not getting any data in the list. However, the list does show exactly the same number of empty list items as the number of items available in the data obtained from API. If I log the data inside the subscribe method browser logs data obtained from api but when I log the data outside subscribe method browser logs undefined object. I have attached my codes. I will appreciate any form of help and advice.
I tried appplying *ngIf condition to only make the list visible once the data is already subscribed in ngOnInit parent ul tag of li as suggested in one of the other posts.
branch-list.component.ts
constructor(private service : BranchService) { }
ngOnInit() {
this.service.getAll()
.subscribe((data: Branch[]) => {
this.branches = data;
console.log(this.branches);
});
console.log(this.branches);
};
branch-list.component.html
<ul class="list-group-flush" *ngIf="branches">
<li *ngFor="let branch of branches; let serialNo = index" class="list-group-item">
<span hidden>{{branch.Id}}</span>
{{ serialNo+1 }}. {{ branch.BranchCode }} {{ branch.Description }}
</li>
</ul>
<ul>
console of browser
Angular is running in the development mode. Call enableProdMode() to enable the production mode.
undefined
(7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {id: 1, branchCode: "KTM", description: "Kathmandu"}
1: {id: 2, branchCode: "PKH", description: "Pokhara"}
2: {id: 3, branchCode: "HTD", description: "Hetauda"}
3: {id: 4, branchCode: "MHN", description: "Mahendranagar"}
4: {id: 5, branchCode: "JHP", description: "Jhapa"}
5: {id: 6, branchCode: "KTM", description: "Kathmandu"}
6: {id: 7, branchCode: "PTN", description: "PTN"}
length: 7
__proto__: Array(0)
The list is supposed to show the data as logged in the console.Console logs data as expected. But in the page, empty list is shown. The empty list only updates and shows the value of serial no but both branchcode and descriptions are blank.
解决方案
Initially set branches = null;
Instead of performing API call in ngOnInIt try in ** ngAfterViewInit** - place where DOM is rendered
ngAfterViewInit() {
this.service.getAll()
.subscribe((data: Branch[]) => {
this.branches = [...data];
console.log(this.branches);
});
};
<ul class="list-group-flush" *ngIf="branches && branches.length">
<li *ngFor="let branch of branches; let serialNo = index" class="list-group-item">
{{ serialNo+1 }}. {{ branch.BranchCode }} {{ branch.Description }}
</li>
</ul>
<ul>
With my understanding i think would work try and update
推荐阅读
- python - Python:不从线性同余生成器函数返回值
- c# - 应用程序启动事件 SpecFlow
- java - 需要使用分隔符拆分字符串并将其值存储在构造函数(Java)中
- forms - 操作方法:具有一组表单的表单,其中包含另一个集合
- python - 简单的 LED 显示项目没有打印到控制台我想要的方式
- dart - 如何在 DartPad 中导入库?
- java - 问题是 - 如何检查一个数字是否是素数
- c++ - 使用 auto vs const auto& 临时保留方法调用的结果
- java - Fat Jar 中的 Apache Camel Timer Nullpointer 异常
- javascript - 我需要获取值 > 0 的密钥