从异步添加的动态添加的超链接中调用角度函数

问题描述 投票:0回答:1

虽然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....
}
angular function hyperlink initialization click
1个回答
0
投票

您可以根据您的情况调整先前的答案。另一个答案挂钩中的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
      }
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.