从异步添加的动态添加的超链接调用 angular 函数

Calling angular function from dynamically added hyperlink which is added asyncronously

虽然 ngOnInit 我调用了异步获取变量的函数。 之后,我想使用该可变数据在组件模板页面上创建一些超链接。 并且超链接必须在点击时调用一些函数。 由于

,该部分无法正常工作
Angular doesn't understand the events of dynamically added elements

但是这个解决方案对我没有帮助,因为 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
      }
    );
}