When Renderer2 chooses an element using the selectRootElement method, its content vanishes

Trying to implement a tab component using Renderer2 to manipulate the selected tab element and apply CSS classes for styling, I encountered an issue where the HTML element disappears entirely from the DOM:

Below is the template for the tab structure:

<div class="detail-nav">
    <div class="nav-item-1">
      <a routerLink="main-config" routerLinkActive="active" (click)=actionItem1()>
        <span>Main config</span>
      </a>
    </div>
    <div class="nav-item-2">
      <a routerLink="sub-config" routerLinkActive="active" (click)=actionItem2()>
        <span>Handling data</span>
      </a>
    </div>
    <div class="nav-item-3">
      <a routerLink="editing" routerLinkActive="active" (click)=actionItem3()>
        <span>Editing</span>
      </a>
    </div>
<div>

I tried ensuring the anchor tag had the same height as its parent div by adding some custom CSS,

and then using Renderer2 like this:


...

constructor(private route: ActivatedRoute, private renderer: Renderer2) {}

...

let elm = this.renderer.selectRootElement(".nav-item a");

this.renderer.addClass(elm, 'nav-item');

Applied CSS:

.nav-item {
  background-color: LightBlue;
}

However, the anchor tag disappeared from the DOM after executing:

this.renderer.addClass(elm, 'nav-item');

What could be causing this issue?

Is there something wrong with how selectRootElement functions?

If anyone has any insights or ideas, they would be greatly appreciated.

I did verify in devtools that the correct element was being referenced by the elm variable during debugging.

Answer №1

The standard operation of the selectRootElement() function is as described. For more information, you can refer to the official documentation.

If you wish to retain content, simply provide a second (boolean) parameter like this:

let element = this.renderer.selectRootElement(".nav-item a", true);

Answer №2

To achieve your goal, you can utilize the @viewChild method.

import { Component, ElementRef, ViewChild, Renderer2 } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild('test') test: ElementRef;

  constructor(private renderer: Renderer2) {}

  addActiveClass() {
    this.renderer.addClass(this.test.nativeElement, 'active');
  }

  removeActiveClass() {
    this.renderer.removeClass(this.test.nativeElement, 'active');
  }
}

<button class="btn btn-primary" (click)="addActiveClass()">Add Class</button>
<button class="btn btn-danger" (click)="removeActiveClass()">Remove Class</button>
<p #test>Here it is </p>

You can find the example on codesandbox

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

How can I have the image appear in the beginning of the TextField material-ui instead of on the side?

Is there a way to seamlessly integrate an image within a TextField, similar to an InputAdornment but located at the start of the TextField? I don't want the image to appear as an icon alongside the text input area, like with a search icon next to a qu ...

The implementation of async await within a switch case statement is failing to function properly

Is it possible to wait for the resolution of a promise within a switch case statement by using the keyword await? I am facing an issue with my Angular component where the following code is causing crashes in my application. switch (this.status) { ...

Ways to determine if an element has exceeded its container's boundaries

After creating the codesandbox, I have developed a webapp that heavily relies on user input. To keep it simple for demonstration purposes, I am displaying various authors on an A4 formatted page using `page` and `font-size` with the `vw` unit for responsiv ...

Learn how to adjust the background color of a div when the text input field is in focus

When rendering the page, <div id="container" tabindex="0"> <input id = "input" type="text" /> </div> In the CSS stylesheet, #container::focus{ background-color: "red" } I am look ...

The row in the table is not reaching its maximum height

Trying to design a layout with a topbar followed by a split layout has posed some challenges. The main issue I encountered was the need for the width and height to adjust automatically based on the browser size. To address this, I attempted to use a table ...

What is the method for customizing the hover color in a mantine.ui menu?

I've been attempting to modify the menu color when hovering over it, but unfortunately, it's not working. Could anyone provide guidance on how to change the hover color in mantine.ui menu? ...

Having trouble resolving all parameters for the HomePage in Angular 2 and Ionic

What could be the issue in my code? I am attempting to utilize cordova-camera-plugins and Ionic native with Ionic 2, but upon running ionic serve, I encounter this Runtime Error: "Can't resolve all parameters for HomePage: ([object Object], [object Ob ...

What could be causing my table to malfunction in IE8?

Is it just me, or do my CSS tables not work on IE8? <div class="main-table"> <div class="row"> <a class="secondary-table" href="#"> <div class="secondary-row"> <div class="secondary-cell"> ...

A guide on adjusting input field height for different screen sizes, from mobile to desktop

Currently, I am working on a project that involves implementing a search input field and button within the navbar. In the mobile view, this form will be nested inside the toggle section (I'm not entirely sure if this is the correct term, but essential ...

To see website changes, refreshing with Ctrl + F5 is necessary in the browser

I have a simple website that uses only HTML and CSS. Whenever I upload new files to the site, they do not appear in the browser until I perform a hard refresh by pressing CTRL + F5. Does anyone have any suggestions on how to fix this issue? ...

To keep a link active, it needs to remain in a pressed state until a new

I was experimenting with HTML and CSS, but I couldn't get it to function as desired. What I am trying to achieve is that the first link/tab should appear pressed when the site is opened. It should then change to an unpressed state when another link i ...

Angular ESLint Error: Sorting issue with Decorated class members

While transitioning a TSLint Angular project to ESLint, I ran into an issue configuring @typescript-eslint/member-ordering. My goal is to maintain the decorated setters after other decorated fields: // place before decorated setter @Input() foo: boolean; @ ...

Interested in embedding DocuSign within an Angular application using an iframe?

Welcome to a brand new image opportunity! https://i.sstatic.net/Cj05w.png I am looking to integrate Docusign for users to sign PDF documents. The plan is to embed it in an iFrame. Currently, the backend is developed using .NET Core and the frontend use ...

When adjusting the viewport size, CSS animated elements may shift unexpectedly in Firefox and Safari, while Chrome displays them correctly

This example demonstrates a simple code snippet: body { display: flex; justify-content: center; align-items: center; height: 100vh; width: 100vw; } .container { animation: moves 5s ease 0s normal forwards; /* transform: trans ...

JavaScript slice() method displaying the wrong number of cards when clicked

In my code, I have a section called .registryShowcase. This section is designed to display logos and initially shows 8 of them. Upon clicking a button, it should load the next set of 8 logos until there are no more left to load (at which point the button ...

What are the benefits of incorporating frontend libraries into our projects?

Currently working on a web page using Vue.js, without a backend at the moment. In need of tabs, I explored the options and came across vue-tabs-component. However, to proceed with the installation, the following command is required: npm install vue-tabs- ...

Activate dropdown menu link when tapped twice on tablet devices

I am trying to implement a dropdown navigation link feature on tablets where the child menu div drops down only on the second click. This functionality already works on iPads, but on Android and Windows tablets, the link is triggered at the same time as th ...

What strategies can be implemented to avoid the delay in loading background content on a website?

Currently, I am working on a website built in aspx.net using the Microsoft Web Developer 2010 Express application. My goal is to create a dynamic background that changes as users scroll down the page and reverts back to the previous image when scrolling up ...

What is the best way to ensure that consecutive if blocks are executed in sequence?

I need to run two if blocks consecutively in TypeScript, with the second block depending on a flag set by the first block. The code below illustrates my scenario: export class Component { condition1: boolean; constructor(private confirmationServic ...

Incorporating media queries in Angular5 with Sass and the latest version of Bootstrap (4.1.3)

Currently, I am working on a project with multiple pages. The web version of the project is almost complete, and now I need to focus on making it responsive. Since I am new to Angular, I am seeking advice on how to add media queries in Angular 5 using SASS ...