Issue
In my list-users.component.ts, I use private ref: ChangeDetectorRef
here is the code below for reference.
export class ListUsersComponent implements OnInit {
public users: any[];
constructor(private ref: ChangeDetectorRef,
private zone: NgZone) {
this.ref.detectChanges();
}
ngOnInit() {
this.loadUser();
}
loadUser() {
const us = this.userService.getUsers('').subscribe(j => {
this.users = j; //binds the code but does not show on page load
});
this.subscriptions.push(us);
}
trackByFn(index: number, users: any){
return users.id;
}
}
Here is my HTML template list-users.component.html shown below.
<tr align="center" *ngFor="let user of users; index as i; trackBy: trackByFn">
<td>{{user?.id}}</td>
<td>{{user?.userName}} </td>
<td>{{user?.occupation}}</td>
<td>{{user?.companyName}}</td>
<td>{{user?.role}}</td>
<td>{{user?.email}}</td>
<td>{{user?.ein}}</td>
<td><a class="btn btn-clean font-weight-bold btn-sm cursor-pointer" type="button" (click)="editUser(user?.id)">Edit</a></td>
</tr>
Now this error shows which is from the HTML template line *ngFor="let user of users
ERROR TypeError: Cannot read properties of null (reading 'users')
at ListUsersComponent_Template (list-users.component.html:68:73)
at executeTemplate (core.mjs:9618:1)
at refreshView (core.mjs:9484:1)
at detectChangesInternal (core.mjs:10837:1)
at ViewRef$1.detectChanges (core.mjs:21414:1)
at new ListUsersComponent (list-users.component.ts:217:26)
at NodeInjectorFactory.ListUsersComponent_Factory [as factory] (list- users.component.ts:266:4)
at getNodeInjectable (core.mjs:3565:1)
at instantiateAllDirectives (core.mjs:10298:1)
at createDirectivesInstances (core.mjs:9647:1)
I tried using trackBy
with detectChanges()
but it shows null
error for users. How can I check my change detection when page is loading and data is coming from service which I bind it in subscription.
Solution
Solved this by adding this.ref.detectChanges();
after model bind and removed it from contructor.
loadUser() {
const us = this.userService.getUsers('').subscribe(j => {
this.users = j;
this.ref.detectChanges(); //added it here after model binding
});
this.subscriptions.push(us);
}
then used this keyvalue
documentation and smaller working example , here is my HTML template.
<tr align="center" *ngFor="let user of users | keyvalue"> //added this keyvalue
<td>{{user.value?.id}}</td>
<td>{{user.value?.userName}} </td>
<td>{{user.value?.occupation}}</td>
<td>{{user.value?.companyName}}</td>
<td>{{user.value?.role}}</td>
<td>{{user.value?.email}}</td>
<td>{{user.value?.ein}}</td>
<td><a class="btn" type="button" (click)="editUser(user.value?.id)">Edit</a></td>
</tr>
Answered By - Naman Kumar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.