user8053092
user8053092

Reputation: 165

How to append html content in angular 2 / typescript

I want to append HTML content into a div('single-pane') using insertAdjacentHTML but nothing happens. Not sure what I am missing here.

Here is my HTML content which I am trying to append---> component.html

  <div #notification class="notification-top-bar" style="display: block;">
  </div>

Here is my typescript code where I am appending---> component.ts

export class SiteNotificationComponent implements OnInit {
  @ViewChildren('notification') private notificationsElements:  QueryList<ElementRef>;
  parentClass: any;

  constructor() {}
  ngOnInit() {} 
 
  ngAfterViewInit() {
    this.parentClass = document.getElementsByClassName('single-pane')[0];
    this.parentClass.insertAdjacentHTML('afterbegin', 'notificationsElements');
  }
}

Upvotes: 2

Views: 4270

Answers (1)

Prachi
Prachi

Reputation: 3574

Use ViewChild instead of ViewChildren if you have only one element of notification type. And declare it of the type ElementRef.

export class SiteNotificationComponent implements OnInit {
  @ViewChild('notification') el:ElementRef;
  parentClass: any;

  constructor() {}
  ngOnInit() {} 

  ngAfterViewInit() {
    this.parentClass = document.getElementsByClassName('single-pane')[0];
    this.parentClass.insertAdjacentHTML('afterbegin', this.notificationsElements.nativeElement.innerHTML);
  }
}

Upvotes: 2

Related Questions