Manipulating a <DIV> style within an Angular 8 project

Looking to change the display style? Check out this template:

<div style="display: none" #myDiv />

There are 2 methods to achieve this:

  1. Method 1: Directly

    if (1===1) this.myDiv.style.display = "block";

  2. Method 2: Using @ViewChild

    @ViewChild('myDiv', { static: false}) myDiv
    if (1===1) this.myDiv.style.display = "block";

Unfortunately, neither of these approaches seem to be working.

Answer №1

To achieve this, you can utilize the ElementRef in the following manner.

HTML Code snippet:

<div class="my-div" style="display: none" />

Typescript (TS) Code snippet:

export class MyComponent implements AfterViewInit  {

  myDiv;

  constructor(private elementRef:ElementRef) {}

  ngAfterViewInit() {

    this.myDiv = this.elementRef.nativeElement.querySelector('.my-div');
  }
}

You can then modify styles using the myDiv variable like so.

this.myDiv.style.display = 'block';

Check out a StackBlitz Demo for reference.

Answer №2

Implement ngStyle:

<div [ngStyle]="{'display': isActive ? 'block' : 'none'}">
    ...
</div>

The variable isActive should be assigned based on the conditions defined in the .ts file.

Answer №3

If you want to apply styles, you can utilize the Renderer2 method. The setStyle prototype is structured as shown below:

setStyle(el: any, style: string, value: any, flags?: RendererStyleFlags2): void

Parameters:

el: any,     Refers to the element where the style will be applied.

style:  string,  Indicates the name of the style.

value:  any,      Represents the new value for the style.

flags   RendererStyleFlags2,  Optional flags for different style variations. By default, no flags are set.

It is recommended to avoid using ElementRef due to security concerns related to direct DOM access. Instead, prefer using Renderer2 to set styles.

For a demonstration example, check out:

https://stackblitz.com/edit/renderer2-example-2-oryw2m?file=src/app/app.component.ts

Here's a code snippet as an example:

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

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

  constructor(private renderer: Renderer2) {}

  ngAfterViewInit() {
    this.renderer.setStyle(this.test.nativeElement, 'backgroundColor', 'red');
    this.renderer.setStyle(this.test.nativeElement, 'color', 'white');
  }
}

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

Aligning multiple items to the right using Flexbox

While it's common knowledge how to align one item to the right in flexbox, what about aligning multiple items, like the last two elements, to the right and the rest to the left? Take a look at this example where I want elements with the class .r to be ...

NestJS TypeORM InjectRepository throwing an error: "Cannot access property 'prototype' of undefined"

Encountering an issue while trying to unit test. Here is the error message that I received: TypeError: Cannot read property 'prototype' of undefined export class UserService { constructor(@InjectRepository(User) private readonly userRepository ...

To prevent the page focus from shifting, make sure to force click on a blank link

My question involves an empty link: <a href="#" id="stop-point-btn">+ add stop-point</a> This link is connected to a JavaScript function: $("#stop-point-btn").bind("click", addStopPoint); The JS function simply inserts content into a specif ...

Removing a selected row from a data table using an HTTP request in Angular 2

I am working with a table that has data retrieved from the server. I need to delete a row by selecting the checkboxes and then clicking the delete button to remove it. Here is the code snippet: ...

How can I change the Safari blue outline to black?

I have an input field and I have applied the following CSS to it: input:active, input:focus { outline: 1px auto rgb(16, 16, 16) !important; outline-offset:0px; } However, when I tested it using , the input field still had a blue outline: I was hoping ...

Struggling to make Cypress react unit testing run smoothly in a ReactBoilerplate repository

I have been struggling for the past 5 hours, trying to figure out how to make everything work. I even recreated a project's structure and dependencies and turned it into a public repository in hopes of receiving some assistance. It seems like there mi ...

Redirecting to child routes based on conditions

I encountered a situation where I need to lazily load child routes and display them conditionally: const routes: Routes = [ { path: '', component: MainComponent, canActivate: [AuthGuard], children: [ { path: &apos ...

Collaborate and apply coding principles across both Android and web platforms

Currently, I am developing a web version for my Android app. Within the app, there are numerous utility files such as a class that formats strings in a specific manner. I am wondering if there is a way to write this functionality once and use it on both ...

Troubleshooting issue with Vue3 - TS Custom State Management

Issue: I am facing a challenge in transferring data between two separate components - the main component and another component. Despite attempting to implement reactive State Management based on Vue documentation, the object's value remains unchanged ...

What is the best strategy for managing pagination when dealing with a large number of pages?

Up until now, I have understood that pagination only links different pages together. This works fine when dealing with a limited number of pages or posts to display. However, what if I have 30 or more pages to paginate? Wouldn't it be impractical to c ...

What is the process for defining an outcome when a draggable element is placed into a droppable area using Jquery?

Currently, I am working on a task where I need to increase the value of a counter (var counter = 0;) every time a draggable image is dropped into a dropzone, which is also an image rather than a div. $( "#goldbag" ).draggable({ revert: "invalid", containm ...

How to display HTML on top without altering the viewport in React?

I am trying to display a component <Top /> above another component <Bottom /> in React. The code structure is as follows: ... [top, setTop] = useState(false); [bottom, setBottom] = useState(true); ... return ( <div> top && (< ...

Eliminate border around image

I've been trying to get rid of the image border using different methods img { border: 0px; } I even attempted to remove it from the browser console with this code border: none !important This is what my html code looks like <div id="startD ...

The "Read more" feature is not functional on mobile devices

I am encountering issues with my Wordpress blog on mobile screens. The "read more" button is not functioning, and the screen size does not fit properly on mobile devices. Visit abood250.com for more information. CSS Styling: /* =Global ----------------- ...

Adding a class dynamically to a <span> based on the value of a field or property

Learning Angular is still new for me, so please be patient. I have a TagComponent that includes a Color-enum and one of those colors as a property. I want Angular to automatically assign this color as a class so that Semantic UI can style it accordingly. ...

How to align a list item to the right using CSS

I'm having trouble aligning items in a list to the right and adjusting their width based on content length. Unfortunately, I haven't been able to make it work despite multiple attempts. Take a look at my code snippet below: .messages { over ...

The issue in Angular2 viewmodel where the boolean value fails to update the *ngIf template

I'm seeking assistance with an unusual issue in my Angular2 and Typescript application. Within my template, I have the following HTML utilizing ngIf: <div *ngIf="loading" class="row"> <div class="small-3 small-centered columns" > ...

The async/await feature in Typescript fails to trigger updates in the AngularJS view

Currently, I am utilizing Typescript 2.1 (developer version) to transpile async/await to ES5. An issue I have encountered is that when I modify any property linked to the view within my async function, the view does not automatically reflect the updated v ...

Listening for keypress events on a div element using React

I'm currently struggling with implementing a keypress listener on a component. My goal is to have my listener activated whenever the "ESC" key is pressed, but I can't seem to figure it out. The function component I am working with is quite stra ...

Angular // binding innerHTML data

I'm having trouble setting up a dynamic table where one of the cells needs to contain a progress bar. I attempted using innerHTML for this, but it's not working as expected. Any suggestions on how to approach this? Here is a snippet from my dash ...