Insert elements within the <li> tags within an ordered list in an Angular application

Within the component.html file of my Angular project, I have the following code snippet:

  <li *ngFor="let activity of dto.activities | sortHistoryActivity; trackBy: trackByFn">
    <span>
      <a (click)="scrollToHistoryActivity(activity.firstTaskId, activity.firstActivityId)">{{activity.title}}</a>
    </span>
    <p class="timestamp">{{activity.startTime | date:"dd.MM.yyyy, HH:mm:ss"}}</p>
  </li>
</ol>

I am looking to insert additional objects between specific <li> elements without resetting the numbering sequence. These inserted objects should not have a number associated with them.

Please excuse any lack of clarity as this is my first question on here.

For an example image, please refer to the link below:

https://i.sstatic.net/gcFOD.png

To elaborate further: In this application, each action is listed with a corresponding number indicating its order of occurrence. My goal is to include certain HTML elements between two list items without affecting the numbering sequence (as illustrated in the provided image).

Answer №1

Consider the HTML snippet below:

<ol #orderedListRef>
  <li>first</li>
  <li>second</li>
  <li>third</li>
  <li>fourth</li>
  <li>fifth</li>
  <li>sixth</li>
</ol>

This TypeScript code illustrates how to target the fourth list item and insert content after it:

@ViewChild('orderedListRef') olRef: ElementRef<HTMLOListElement>

.
.
.

// Access the native element using ViewChild
const ol: HTMLOListElement = olRef.nativeElement;

// Find the fourth list item which is a direct child of the ordered list
const fourthElement = ol.querySelector("li:nth-child(4)");

// Create an element to be inserted after the list item
const divToAppend: HTMLDivElement = document.createElement("div");
// Add desired content to the new element
divToAppend.innerHTML = "<h1>example text</h1>";

// Insert the new element after the listItem
fourthElement.after(divToAppend);

In this scenario, the result will be:

<ol #orderedListRef>
  <li>first</li>
  <li>second</li>
  <li>third</li>
  <li>fourth</li>
  <h1>example text</h1> <-----
  <li>fifth</li>
  <li>sixth</li>
</ol>

Answer №2

If you're looking to dynamically add elements based on certain conditions, one way to do it is by utilizing the ng-container component provided by Angular. Here's an example:

<ol>
    <ng-container *ngFor="let activity of dto.activities | sortHistoryActivity; trackBy: trackByFn">
    <!-- Check if activity does not have a number -->
        <p *ngIf="!activity.number">Insert HTML here</p>

     <!-- Check if activity has a number -->
        <li *ngIf="activity.number">
            <span>
              <a (click)="scrollToHistoryActivity(activity.firstTaskId, activity.firstActivityId)">{{activity.title}}</a>
            </span>
            <p class="timestamp">{{activity.startTime | date:"dd.MM.yyyy, HH:mm:ss"}}</p>
        </li>
    </ng-container>
</ol>

Answer №3

If the numerical value holds significance, my suggestion would be to store it within the model and have control over its display.

To directly address your query, you have the option to specify the starting number of an ordered list (ol) using the start attribute.

<p>For example</p>
<ol>
  <li>Text</li>
  <li>Text</li>
  <li>Text</li>
</ol>

<p>Insert HTML code snippet</p>
<ol start="4">
  <li>Text</li>
  <li>Text</li>
  <li>Text</li>
</ol>

This approach still necessitates keeping track of certain information, hence I believe it would be more efficient to store the order in your model and link your HTML to the respective order number as outlined in the model.

dto: {
  activities: {
    order: 1,
    name: 'Text'
  },
  // ... etc
}
<ul>
  <li *ngFor="let activity of dto.activities">
    {{activity.order}}. {{activity.name}}
  </li>
</ul>

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

Diverse Templates within a Single Angular Component

Is there a way to reuse a single component with varying content? I have a component called quick-links that extends the dashboard-panel component and includes a title and content. I am looking to reuse the quick-links component with different titles and co ...

Encountered an issue while resolving dependency tree for angular tslib

When running npm install, I encountered the error shown in this image: https://i.stack.imgur.com/PInQE.png The CLI version is Angular CLI: 9.1.8. Any assistance would be greatly appreciated. Thank you! ...

Something went wrong: [ERR_UNSUPPORTED_ESM_URL_SCHEME]: The default ESM loader only supports URLs with a scheme of file, data, and node

Every time I attempt to run yarn dev to start a discord bot, I encounter the following error. The bot is built using TypeScript. I have attempted to update the Node.js version using nvm, but to no avail. I even tried using older versions of Node.js, going ...

Encountering problem when creating new app with Angular CLI version 6.0.4 and specifying the

I just used npm to globally install angular cli version 6.0.4 with the command `npm install -g @angular/cli`. However, when I attempt to create a new project using `ng new my-first-app`, an error message is displayed: The input for the schematic does not ...

Angular 5 interception mechanisms

I have been trying to set up interceptors in my Angular 5 project, but unfortunately they are not working. I injected the interceptor in the file app.module.ts, however, I am still encountering errors. Additionally, I added a console.log statement in the i ...

Restful: Numerous scenarios for a single resource (is it the same API endpoint?)

In this scenario, there are two different approaches to creating a user: If the user is created by an administrator, no password is provided initially. The user must choose a password on the activation page. If the user creates their own account, a passw ...

ESLint does not include Cypress files in its checking process

My Angular 13 project is coded in Typescript and utilizes eslint for code checking. Recently, I integrated Cypress into the project. However, I noticed that when I run the command ng lint, it does not scan the files within the /cypress directory. Interesti ...

Angular 2: Challenges with Utilizing Set - Limited Browser Support and Iteration Issues

I am currently developing an Angular 2 Web Application. My goal is to add users to a game by utilizing checkboxes on a screen. When a checkbox is selected, I plan to add the user to a set. mySet = new Set(); this.mySet.add(e); Once a user clicks the "Ad ...

The "library" is encountering errors due to missing dependencies, specifically @angular/material/form-field

I've been working with a shared component library project that has been running smoothly for a while now. Recently, I decided to replace some of the custom components with Angular Material components. However, after adding NgMat to the library project ...

Steps to resolve the error "Cross-Origin Request Blocked: The Same Origin Policy prohibits reading the remote resource" in a project using Angular and .NET

Whenever I make an HTTP GET request to our API endpoints, I encounter errors indicating that the CORS header 'Access-Control-Allow-Origin' is missing. Our system consists of a SQL Server database connected to a .NET API with an Angular 7 front e ...

How to implement automatic clicking using Material Angular components

Looking to incorporate layout tabs from Angular Material into my project: https://material.angular.io/components/tabs/overview Interested in implementing auto-click functionality - how can I instruct Angular to simulate clicking on the "Tab1" link, waiti ...

Importing JS files or SDKs in Angular that are not modules

Currently, I am incorporating the Avaya SDK (which consists of 3 JS files) into my Angular project. However, when attempting to import it, I encounter an error stating that it is not recognized as a module. Any suggestions on how to resolve this issue? Th ...

Learn how to retrieve data from the console and display it in HTML using Angular 4

Need help fetching data inside Angular4 HTML from ts variable. Currently only able to retrieve 2 data points outside the loop. Can anyone assist with pulling data inside Angular4? HTML: <tr *ngFor="let accept of accepts"> ...

Ensure that the default boolean value is set to false rather than being left as undefined

I have a specific type definition in my code: export type ItemResponse = { .... addedManually: boolean; .... } Whenever I parse a JSON response into this type, I encounter an issue: const response = await fetch( `https://api.com` ); con ...

React TypeScript - creating a component with a defined interface and extra properties

I'm completely new to Typescript and I am having trouble with rendering a component and passing in an onClick function. How can I properly pass in an onClick function to the CarItem? It seems like it's treating onMenuClick as a property of ICar, ...

Preventing Right-Click on Angular Material's CDK Overlay Container: A Step-by-Step Guide

When implementing a mat-menu as a context menu on a canvas object, I encountered an issue where the default browser context menu would appear when right clicking on the canvas object. This default context menu would overlap the actual context menu I inte ...

Acquiring an element through ViewChild() within Angular

I am in need of a table element that is located within a modal. Below is the HTML code for the modal and my attempt to access the data table, which is utilizing primeng. <ng-template #industryModal> <div class="modal-body"> <h4>{{&a ...

Is it possible to define a class prior to exporting it in typescript/angular? | TSLint warning: unused expression, assignment or function call expected

Coming from the realm of React, I am well-versed in the fundamental concepts of launching an application with an index.js, avoiding direct involvement with HTML, and utilizing import and export statements to share views among different JavaScript files. In ...

My Angular-based todo application has encountered an error notification from the system

Every time I try to post something, the system responds with a 405 error message in the console. I'm not sure what caused this issue or how to resolve it. Alternatively, if I click the done button, the console displays a 500 error message. Here is t ...

Angular 2 web SQL definitions

Currently, I am developing an electron app with Angular 4 and need to integrate a database. My preference is to utilize websql, but I am facing challenges importing the necessary typings. Upon adding @types/websql to my project and writing the code: cons ...