0

I have an array of objects. I have two tables on the screen. I want n-1 elements in top table and the last element to be displayed in bottom column.

HTML top table:


<th>name</th>
<th>age</th>
<tr *ngFor="let key of array">
<td> {{key.name}}</td>
<td> {{key.age}}</td>

HTML bottom table:
<th></th>
<th>age</th>
<tr *ngFor="let key of array">
<td></td>
<td> {{key.age}}</td>

suppose if there are 5 elements, 4 should be displayed at top and last at bottom. In api response I am getting a single array of objects and last object should always be in the bottom table. Also, last table does not have a name column. It returns a string "Final Name". Can this be used to detect that if name === Final Name then remove it from array and show it else where? What should be the for loop condition for it? Should I slice last element from array and store it in temp array in .ts file?

2 Answers 2

1

You could create a variable to store the last array object in your ts file then pop the array to this variable. E.g:

component.ts:

export class YourComponent {
lastItem: YourType;

...

lastItem = myArray.pop();

This will remove the last item and assign it to lastItem variable which can be used to populate your bottom table.

HTML bottom table:

<th></th>
<th>age</th>
<tr>
<td></td>
<td> {{lastItem.age}}</td>
Sign up to request clarification or add additional context in comments.

3 Comments

i was getting response like: this.array = res; const finalName = this.array.pop(); in html i am trying ngFor="let key of finalName" <td>{{key.finalName}}</td>
this is not working out. I am relatively new to angular
I have edited to add more detail. In your bottom table, no need to do the ngFor loop as there is only one item in that table. Just reference the variable by name within the table cell directly, so {{lastItem.age}} (or whatever you have called your variable) instead of {{key.age}} as you are not using the for loop 'key' variable now. Make sure the variable is declared in your component class definition, not inside a function, so it is available to your template.
1

Ok first of all use the *ngFor like this

*ngFor="let item of items; let i = index"

And you can apply condition like

*ngIf="i!=array.length"

And by using index you can print those last array elements separately

Comments

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.