In angular 6 application, I am using the "ng-select" https://github.com/ng-select/ng-select#getting-started select box and firing the "change" event to retrieve data from an API method and assign them to an observable, then using the async pipe in my html to listen to an array property of this observable and display it in a table, although I am retrieving the data at the table, but at some instant it throws an error because the property evaluates to "null",
AgentBranchAssignmentComponent.html:72 ERROR TypeError: Cannot read property 'users' of null
at Object.eval [as updateDirectives] (AgentBranchAssignmentComponent.html:72)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:11054)
at checkAndUpdateView (core.js:10451)
at callViewAction (core.js:10692)
at execEmbeddedViewsAction (core.js:10655)
at checkAndUpdateView (core.js:10452)
at callViewAction (core.js:10692)
at execComponentViewsAction (core.js:10634)
at checkAndUpdateView (core.js:10457)
at callViewAction (core.js:10692)
so please advise: 1) why this error is happening, and how to avoid it? 2) is this the best solution for such scenario? 3) how do I clear the table if i clear the selection?
this is the and the table with the ngFor "ng-select" configuration in html:
<ng-select
(change)="getAgentsForBranch($event)"
[items]="branches">
</ng-select>
<tbody *ngIf="userPage && (userPage | async).users">
<tr *ngFor="let u of (userPage | async).users">
<td>{{u.firstName + " " + u.lastName}}</td>
<td>{{branchName}}</td>
</tr>
</tbody>
and here is the ts:
userPage: Observable<AllUserListPage>;
getAgentsForBranch(event) {
if(!event){
// here i am clearing the selction and want to clear data in the table also
this.branchName= '';
return;
}
const branchId = event.branchId;
this.branchName = event.name;
this.userPage = this.obexService.getUsersForBranch(branchId, 0, 50, 'OLDEST', true)
}
try to use ng-container
with async
pipe and when you have data will be available by result variable
<ng-container *ngIf="userPage | async as result ">
<tbody >
<tr *ngFor="let u of result.users">
<td>{{u.firstName + " " + u.lastName}}</td>
<td>{{branchName}}</td>
</tr>
</tbody>
</ng-container>
check this demo 🚀