虽然ngOnInit我调用了异步获取我变量的函数。之后,我想使用该变量数据在组件模板页面上创建一些超链接。而且,超链接必须在单击时调用某些功能。由于
,该部分不起作用Angular doesn't understand the events of dynamically added elements
Calling angular function from dynamically added hyperlink
但是该解决方案对我无济于事,因为ngAfterViewInit()不能获取我的异步变量。
所以我该怎么做...
ngOnInit() {
this.somefunction gets me variable .subscribe(
this.testVar='testData';
And here I construct some hyperlinks using this variable
<a [routerLink]="[]" class="image-fav" (click)="someFunc()">this.testVar</a>
}
someFunc() {
doing something....
}
您可以根据您的情况调整先前的答案。另一个答案挂钩中的ngAfterViewInit
是一个通用的用例场景。在您的情况下,可以将元素添加到DOM,触发更改检测(例如,使用detectChanges()
),并将事件侦听器全部添加到ngOnInit
挂钩中。
import { Component, ChangeDetectorRef, ElementRef, OnInit } from '@angular/core';
export class AppComponent implements OnInit {
constructor(private changeDetectorRef: ChangeDetectorRef, private elementRef: ElementRef) { }
ngOnInit() {
this.someService.someFunction().subscribe(
response => {
this.testVar = 'testData';
// construct dynamic element `<a [routerLink]="[]" class="image-fav" (click)="someFunc()">this.testVar</a>`
this.changeDetectorRef.detectChanges();
this.elementRef.nativeElement.querySelector('.image-fav').addEventListener(
'click', this.someFunc.bind(this)
);
},
err => {
// handle error
}
);
}