如何在 angular 2 / typescript 中附加 html 内容

How to append html content in angular 2 / typescript

我想使用 insertAdjacentHTML 将 HTML 内容附加到 div('single-pane') 中,但没有任何反应。不确定我在这里遗漏了什么。

这是我要附加的 HTML 内容---> component.html

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

这是我要附加的打字稿代码---> 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');
  }
}

如果您只有一个通知类型元素,请使用 ViewChild 而不是 ViewChildren。 并将其声明为 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);
  }
}