将事件侦听器添加到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.