将事件侦听器添加到Angular 4中的动态元素吗? [英] Adding event listener to dynamic element in Angular 4?

查看:100
本文介绍了将事件侦听器添加到Angular 4中的动态元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些API的描述文本,我将这些文本作为HTML插入DOM.

I have some description text from an API that I am inserting as HTML into the DOM.

<div class="activity-description" [innerHTML]="description"></div>

说明是在ngOninit()中设置的

The description is set within ngOninit();

if (this.eventDetail.description.length > 255) {
   this.description = this.eventDetail.description.substring(0, 255) + '<span class="more-description"> ...Learn More</span>';
}

我正在尝试将事件侦听器添加到ngAfterViewInit()中的更多描述"类中

I am trying to add an event listener to the "more-description" class within the ngAfterViewInit()

var el = this.elementRef.nativeElement.querySelector('.more-description');
    if (el)
        el.addEventListener('click', this.displayFullDescription());

该元素为null,不允许附加事件侦听器.如何将此事件侦听器添加到动态添加的html元素中?

The element is null and does not allow the event listener to be attached. How do I add this event listener to html elements that are dynamically added?

推荐答案

您可以通过调用cdRef.detectChanges手动渲染视图:

You can manually render view by calling cdRef.detectChanges:

constuctor(private cdRef: ChangeDetectorRef) {}

ngOnInit() {
  if (this.eventDetail.description.length > 255) {
    this.description = this.eventDetail.description.substring(0, 255) +
                      '<span class="more-description"> ...Learn More</span>';
  }
}

ngAfterViewInit() {
  this.cdRef.detectChanges();
  var el = this.elementRef.nativeElement.querySelector('.more-description');
}

更新

也许您在此代码中犯了一些错误:

Perhaps you made some mistake in this code:

el.addEventListener('click', this.displayFullDescription());

我不知道displayFullDescription函数的作用.

这是工作示例:

@Component({
  selector: 'event',
  template: `
    <div class="activity-description" [innerHTML]="description"></div>
  `,
})
export class Event {
  @Input() eventDetail: any;

  description: string;

  constructor(private elementRef: ElementRef) { }

  ngOnInit() {
    if (this.eventDetail.description.length > 255) {
       this.description = this.eventDetail.description.substring(0, 255) + '<span class="more-description"> ...Learn More</span>';
    }
  }

  displayFullDescription() {
    this.description = this.eventDetail.description;
  }

  ngAfterViewInit() {
    var el = this.elementRef.nativeElement.querySelector('.more-description');
    if(el) {
      el.addEventListener('click', this.displayFullDescription.bind(this));
    }
  }
}

柱塞示例

Plunker Example

注意:最好将处理程序存储在类属性中,以便以后取消订阅.

Note: It would be better if you store handler in class property so that you can unsubscribe later.

这篇关于将事件侦听器添加到Angular 4中的动态元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆