36

I am using Angular 5.2 in my project and new to the angular framework. My component html is looking like this:-

enter image description here

I want to add the style="top:200px;" dynamically to the highlighted element with class="app-alerts" in the above screenshot in the angular ts code. The div element with class "app-alerts" get added to the DOM on the render.

Please suggest the code changes.

Karan
  • 3,265
  • 9
  • 54
  • 82

4 Answers4

97

I'm super late to this party, but NO! DO NOT USE DOCUMENT.QUERYSELECTOR. That is NOT how you style an Angular DOM element!

<div [ngStyle]="{'top.px': divStyle}">

Then in your component, you have

ngAfterViewInit() {
  this.divStyle = 200; 
}
Chris Stanley
  • 2,766
  • 2
  • 13
  • 18
39

As per our comments, You should be using document.querySelector after a life cycle hook

ngAfterViewInit() {
    (document.querySelector('.app-alerts') as HTMLElement).style.top = '150px';
}
Aravind
  • 40,391
  • 16
  • 91
  • 110
  • 1
    When you need to reach a native element, consider using "Template reference variables" https://angular.io/guide/template-syntax#template-reference-variables-var . For specific dynamic style, prefer @chris-stanley anwser – Hettomei Sep 03 '19 at 13:34
  • 3
    This is not solution for angular, thus the down vote. – makkasi Feb 21 '20 at 11:36
  • 3
    No, this is a really bad practice – nicowernli Sep 14 '20 at 12:56
  • If this is bad practice then how we can apply style to a class which is present in a third party control dynamically in Angular way? – CSS Jun 03 '22 at 07:17
  • Also use of `document` makes this not SSR compatible – Wahrenheit Sucher Aug 09 '22 at 14:38
  • I settled on this solution as nothing seemed to work for setting width of the component inserted in the router outlet into mat-sidenav-content – user3088037 Jun 06 '23 at 16:59
1

I came across a page that has good explanation and sample code to add the style dynamically in Angular 2+. Attach the style dynamically in Angular

Pankaj Shinde
  • 107
  • 1
  • 5
1

I had the same problem, i needed to scroll a div when user scroll a page, and solved my problem with the code below. At the component where you want to capture the scroll:

import { HostListener } from '@angular/core';

@ViewChild('curtain') divCurtain: ElementRef;

export class ComponentX {
    @HostListener('window:scroll', ['$event']) onScrollEvent($event) {
        console.log(window.pageYOffset);
        this.divCurtain.nativeElement.style.top = window.pageYOffset.toString().concat('px');
    }

    ngOnInit(): void { }
}

Only this, i did not create any directive or other code. This HostListener is executed every time the user scroll the page, and i get the window.pageYOffset to send to my div.

I hope it helps.

Fabricio Leite
  • 181
  • 2
  • 4