Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style a html element in typescript / angular

I am trying to set property to html element but getting an error Type 'HTMLCollectionOf' is not assignable to type 'HTMLElement'

Here is my typescript code---

let elem: HTMLElement= document.getElementsByClassName('notification-top-bar');
      setTimeout(elem.setAttribute("style", "display:none;"), this.duration);

Here is my HTML code---

<div class="row">
  <div *ngFor="let n of notifications" class="notification-top-bar" [ngClass]="type" style="display: block;">
    {{message}}  
    <a class="close glyphicon glyphicon-close" (click)="onCloseNotifications($event)"></a>
    <p>{{n}}</p>
  </div>
</div>
like image 235
user8053092 Avatar asked Jan 28 '23 23:01

user8053092


2 Answers

Use ViewChildren to get the elements and set their styles. For that you'll have to add a template reference for the elements using which you can get them in your code. Change your template code to add a reference e.g. #notification:

<div class="row">
    <div *ngFor="let n of notifications" #notification 
         class="notification-top-bar" [ngClass]="type" 
         style="display: block;">
        {{message}}
        <a class="close glyphicon glyphicon-close" 
           (click)="onCloseNotifications($event)"></a>
        <p>{{n}}</p>
    </div>
</div>

Then you can get that in your code like this using QueryList:

import { Component, ViewChildren, QueryList } from '@angular/core';

@Component({ ... })
export class YourComponent  {

  // Get the template elements
  @ViewChildren('notification') private _notificationsElements:  QueryList<ElementRef>;

  ngAfterViewInit() {    

      this._notificationsElements.forEach((element)=>{      
      const htmlElement = element.nativeElement as HTMLElement;
      // Assigning the property directly
      setTimeout(htmlElement.style.display = 'none',this.duration);
      // OR
      // Using the setAttribute method
      setTimeout(htmlElement.setAttribute("style", "display:none;"),this.duration);
    });

  }
}

StackBlitz Demo.

like image 98
Faisal Avatar answered Jan 31 '23 21:01

Faisal


document.getElementsByClassName returns an array and not single Element. you can get element by specifying its index like

document.getElementsByClassName('notification-top-bar')[index]

also i think you have a typo here , it should be display

setTimeout(elem.setAttribute("style", "display:none;"), this.duration);

like image 34
prady Avatar answered Jan 31 '23 22:01

prady