2

I have angular component that get values from back end.

Here is the method in ts.

properties: PropertyDto[] = [];
    getProperties(event?: LazyLoadEvent): void {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }

        this.primengTableHelper.showLoadingIndicator();

        this._propertyService.getProperties(
            this.filterText,
                this.primengTableHelper.getSorting(this.dataTable),
                this.primengTableHelper.getMaxResultCount(this.paginator, event),
                this.primengTableHelper.getSkipCount(this.paginator, event)
        )
        .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
        .subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
            this.primengTableHelper.hideLoadingIndicator();
        });
    }

Some of values in result can be null.

Here is html part for those values

 <td>
    {{record.landlord.name}}
 </td>
 <td>
   {{record.agent.name}}
 </td>

I have errors like

Cannot read property 'name' of undefined

How I can show just blank field and avoid those errors?

Liam
  • 27,717
  • 28
  • 128
  • 190
Eugene Sukh
  • 2,357
  • 4
  • 42
  • 86
  • 1
    Try `{{record?.landlord?.name}}` (question marks) – porgo Apr 11 '19 at 12:24
  • Possible duplicate of [Error if don't check if {{object.field}} exists](https://stackoverflow.com/questions/34910928/error-if-dont-check-if-object-field-exists) – Liam Apr 11 '19 at 12:43

4 Answers4

9

Use ? for safe binding, try this:

{{record?.landlord?.name}}
Liam
  • 27,717
  • 28
  • 128
  • 190
Quan VO
  • 1,258
  • 11
  • 19
1

Better. record? could also be record.landlord? depending on your datasource, i.e. can landlord be undefined if record isn't.

<td>
    {{record? record.landlord.name :''}}
</td>

<ng-container *ngIf="record; else elseTemplate">
              <td>
                {{record.landlord.name}}
              </td>
            </ng-container>
            <ng-template #elseTemplate>
              <td>
                &nbsp;
              </td>
            </ng-template>
Liam
  • 27,717
  • 28
  • 128
  • 190
Robin Webb
  • 1,355
  • 1
  • 8
  • 15
0
<td>
    {{record.landlord? record.landlord.name :''}}
</td>

Checks the value of landlord. If it is truthy by the means of JavaScript, use it. Otherwise use empty string

igorepst
  • 1,230
  • 1
  • 12
  • 20
0

You could use ng ifs to show something different if there is no record for example:

<div *ngIf="record">
    <h1 *ngIf="record.landlord">{{record.landlord.name}}</h1>
    <h1 *ngIf="record.agent">{{record.agent.name}}</h1>
</div>

you can find more information/docs here

mog13
  • 81
  • 3