【问题标题】:How to append html content in angular 2 / typescript如何在angular 2 / typescript中附加html内容
【发布时间】:2018-06-13 05:32:45
【问题描述】:

我想使用 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');
  }
}

【问题讨论】:

    标签: angular typescript angular5 angular2-template


    【解决方案1】:

    如果您只有一个通知类型元素,请使用 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);
      }
    }
    

    【讨论】:

    • 我尝试了你的建议,它附加了 [object HTMLDivElement]
    • 试试 this.notificationsElements.nativeElement.innerHTML。我已经更新了答案。
    猜你喜欢
    • 2017-08-24
    • 2016-12-31
    • 2018-01-01
    • 2020-05-08
    • 1970-01-01
    • 2014-03-29
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多