The problem I'm facing is the detectChanges() which is not working for a component I was thinking that only my local server running be an issue but I tried to use SWAPI to run the test, here is my ListUsersComponent component.
export class ListUsersComponent implements OnInit {
subscriptions: Subscription[] = [];
avatarPic = 'none';
tempData: any[] = [];
constructor(private fb: FormBuilder,
private http: HttpClient,
private ref: ChangeDetectorRef) {
}
ngOnInit(): void {
this.loadUser();
}
loadUser() {
const sub = this.http.get('https://swapi.dev/api/people').subscribe((result:any)=> {
console.log(result); //data is showing here
console.log(result.results); //data is showing here
this.tempData = result.results;
this.ref.detectChanges();
});
this.subscriptions.push(sub);
}
}
Here is the HTML of ListUsersComponent.
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Height</th>
<th scope="col">Mass</th>
</tr>
</thead>
<tbody>
{{avatarPic}}
<tr *ngFor="let data of tempData; let i = index">
<th scope="row">{{ i + 1 }}</th>
<td>{{data.name}}</td>
<td>{{data.height}}</td>
<td>{{data.mass}}</td>
</tr>
</tbody>
</table>
No Result is shown on the HTML page but console.log shows data, here is the snapshot of the console.log below.
a new thing also happened is that I create a duplicate replica of the component it worked flawlessly.
I don't know why this behaviour is happening for a particular page.
I did try to copy replica to the original page thinking that would work and whatever the issue might be sorted out but still this page persists this problem.
The onPush change detection getting missed in this code
ChangeDetectionStrategy.OnPush.In components with the default change detection strategy (no
OnPush),this.ref.detectChanges()can be used to trigger change detection manually.In components with
ChangeDetectionStrategy.OnPush,you can still usethis.ref.detectChanges()to trigger change detection, but it's typically used in specific situations where you need to update the view due to external changes (httpAPI call) that wouldn't automatically trigger change detection.Working Code: stackblitz
Hope this helps :)