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>
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With