1

I have an object that looks like this:

public serviceTable: Services[] = [
  { 1: { service: 'Service 1', description: 'Lorem Ipsum', serviceIsMandatory: true, serviceIsDisabled: true, price: 100, hourlyRate:100, hours: 5} },
  { 2: { service: 'Service 2', description: 'Lorem Ipsum', serviceIsMandatory: true, serviceIsDisabled: true, price: 100, hourlyRate:100, hours: 5} },
  { 3: { service: 'Service 3', description: 'Lorem Ipsum', serviceIsMandatory: true, serviceIsDisabled: true, price: 100, hourlyRate:100, hours: 5} }
];

Now in HTML, I want to output the values of service in my table.

<table mat-table [dataSource]="serviceTable" #matTableService class="mat-elevation-z8">
  <ng-container matColumnDef="service">
    <th mat-header-cell *matHeaderCellDef>Service</th>
    <td mat-cell *matCellDef="let element">{{ element[1].service }}</td>
  </ng-container>

Well, element[1].service works fine and outputs the string Service 1 but this is static and I want to make it dynamic.

I have also tried it with {{element.key | json }} but that outputs nothing. So how can I make it dynamic?

1
  • you will need to loop over the serviceTable array making a td element for each item in the array Commented May 27, 2022 at 21:45

1 Answer 1

2

You can add let i = index; to iterate here.

<table mat-table [dataSource]="serviceTable" #matTableService class="mat-elevation-z8">
  <ng-container matColumnDef="service">
    <th mat-header-cell *matHeaderCellDef>Service</th>
    <td mat-cell *matCellDef="let element; let i = index;">{{ element[i].service }}</td>
  </ng-container>
Sign up to request clarification or add additional context in comments.

2 Comments

Since i starts with 0 and the IDs of my object start with 1, I have received an error. I have now changed the IDs of my object and that works great. Thank you!
You can also give {{ element[i+1].service }} in that case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.