How to Use ngFor to Create a Link for the Last Item in an Array in Angular 7

I need help with adding a link to the last item in my menu items array.

Currently, the menu items are generated from a component, but I'm unsure how to make the last item in the array a clickable link.

ActionMenuItem.component.html

  <div *ngIf="expanded">
  <actionmenuitem *ngFor="let child of line.children" [line]="child" (inWorkspace)="toWorkspace($event)"></actionmenuitem>

ActionMenuItem.Component.ts

  onSelect(){
// If it has children, expand them && flip carat.
if(this.line.children.length > 0){

  this.expanded = !this.expanded;

  if(this.iconName == "expand_more"){
    this.iconName = "expand_less"
  } else {
    this.iconName = "expand_more"
  }

} else {
  this.inWorkspace.emit(this.line);
}

Answer №1

When working with Angular, you have access to the following variables:

  • first
  • last
  • even
  • index
  • odd

To turn the last item into a link, use the following code snippet:

<div *ngFor="let child of line.children; let last = islast">
   <actionmenuitem *ngIf="islast" [line]="child" 
(inWorkspace)="toWorkspace($event)">
    </actionmenuitem>
</div>

Answer №2

Here is a suggestion to try:

View Working Demo

<ng-container *ngFor="let child of line.children;let i=index">

    <actionmenuitem *ngIf="i != (line.children.length-1)" [line]="child" (inWorkspace)="toWorkspace($event)">
    </actionmenuitem>

    <a [routerLink]="[child]" *ngIf="i == (line.children.length-1)">{{child}}</a>
</ng-container>

Answer №3

If you're looking to correct the final flag assignment, consider these options:

  • Try setting it as isLast = last
  • Alternatively, keep it as last but assign it to isLast

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The call stack in mongodb has surpassed its maximum size limit

I am currently executing a method. Method execution var message = "Hello" function1("78945612387", message, null, "Portalsms") Node JS Code function function1(mobileno,body,logExtraInfo,messageType){ request(uri, function (error, resp ...

Submitting a form using jQuery and processing the response

Can a form be submitted using jQuery without utilizing json, ajax, or other methods for handling the result? For example: <form id="loginform"> //some input fields and a submit button. </form> And then with jQuery: $("#loginform").sub ...

Add data to a nested array with Vuex

Currently, I am facing a challenge with adding an object to a nested array in Vue using store / vuex. While I have successfully updated the main comments array with a mutation, I am struggling to identify the specific main comment to which the new reply ob ...

Issue: Encounter StaticInjectorError while working with deployed Angular CLI project

We encountered an issue while attempting to deploy our Angular CLI (v.1.7.1) project on GitHub Pages and Firebase, resulting in the same outcome for both platforms. The ng serve command functions flawlessly on localhost:4200, and everything goes smoothly ...

extract the text content from an object

I am trying to add an object to the shopping cart. The item contains a key/value pair as shown in the following image: https://i.stack.imgur.com/5inwR.png Instead of adding the title with its innerText using p and style, I would like to find another ...

Tips for managing a PHP post request without full knowledge of the variables to retrieve

My form allows users to dynamically add new lines using JavaScript. However, when they click the save button, I am struggling to capture and assign the new data to a variable. The current issue is that once the user adds new rows and clicks save, the rows ...

browsing through a timeline created using HTML and CSS

I am currently working on a web project that involves creating a timeline with rows of information, similar to a Gantt chart. Here are the key features I need: The ability for users to scroll horizontally through time. Vertical scrolling capability to na ...

Unable to substitute a value using the useState hook in React

Whenever I click a key, I attempt to update the value of a variable but it appears not to be working as intended. ↓ The current implementation is not effective and needs improvement import React, { useState, useEffect } from 'react'; const Li ...

Retrieve information from a .json file using the fetch API

I have created an external JSON and I am trying to retrieve data from it. The GET request on the JSON is functioning correctly, as I have tested it using Postman. Here is my code: import "./Feedback.css"; import { useState, useEffect } from " ...

Obtaining only a portion of the text when copying and editing it

I have a React application where I am attempting to copy text from an HTML element, modify it, and then send it back to the user. I have been successful in achieving this, but I am facing an issue where even if I select only a portion of the text, I still ...

Show brief tags all on one line

This image showcases the functionality of the site, specifically in the "Enter a code" column where users can input data using TagsInput. I am seeking to enhance this feature by ensuring that shorter tags are displayed on a single line. While I am aware th ...

Merging Promises in Typescript

In summary, my question is whether using a union type inside and outside of generics creates a different type. As I develop an API server with Express and TypeScript, I have created a wrapper function to handle the return type formation. This wrapper fun ...

Exploring the setTimeout function in JavaScript

As I understand it, the setTimeout function creates a new thread that waits for x milliseconds before executing the JavaScript function. setTimeout(functionName, timeInms); My question is: Is there a way to instruct it to run after all other JS on the pa ...

Leverage the child interface as a property interface containing a generic interface

I'm facing an issue while trying to incorporate typings in React. The concept is centered around having an enum (EBreakpoint) that correlates with each device we support. A proxy wrapper component accepts each device as a prop, and then processes the ...

The start "NaN" is not valid for the timeline in vis.js

Whenever I attempt to make a call, an error message pops up saying Error: Invalid start "NaN". I've looked everywhere online for a solution with no success. Below are the timeline options: timeline: { stack: true, start: new Date(), end: ...

Unable to locate module within the ngModule imports

I am facing a peculiar issue. I have used npm install to add ng-push, imported PushNotificationsModule from 'ng-push', and included PushNotificationsModule in my ngModule imports. Interestingly, both the ng build and ng build --prod commands are ...

Executing a Javascript function when a form is submitted

function validateForm() { alert("Form submitted successfully"); return true; } <form onsubmit="return validateForm()" action="add.php" method="post" id="p1"> <center>Add New Survey</center> <p>&nbsp;&l ...

Algorithm for encryption and decryption using symmetric keys

Can anyone recommend a reliable symmetric-key encryption algorithm that works seamlessly with both JavaScript and Java programming languages? I attempted to implement one myself, but encountered some complications related to encoding. ...

What is causing VSCode's TypeScript checker to overlook these specific imported types?

Encountering a frustrating dilemma within VS Code while working on my Vite/Vue frontend project. It appears that certain types imported from my Node backend are unable to be located. Within my frontend: https://i.stack.imgur.com/NSTRM.png The presence o ...

Passport verification is successful during the login process, however, it encounters issues during registration

I am currently learning about passport.js and session management, and I'm in the process of implementing a local login feature on my website. Here is what I am attempting to achieve: Secret page: Authenticated users can access the secret page, while ...