【问题标题】:How to execute a function, when angular ngFor creates an element in the DOM?当 Angular ngFor 在 DOM 中创建一个元素时,如何执行一个函数?
【发布时间】:2021-03-17 10:30:27
【问题描述】:

我有一个服务器端脚本,它将传感器信息保存到数据库中。然后,此信息应显示在前端。前端是一个角度应用程序。数据库中的传感器信息将显示在基于冰沙包的图表中。在页面加载期间的前端,我在 ngOnInit 函数中调用 API 端点,并返回如下输出:

[
    {
        "id": 1,
        "name": "CPU Usage",
        "frequency": 5,
        "unit": "%"
    },
    {
        "id": 2,
        "name": "Memory Usage",
        "frequency": 4,
        "unit": "GB"
    }
]

然后我将它加载到一个数组中:

  public charts: Chart[] = [];

  constructor(private httpClient: HttpClient, private dataService: ApiService) { }

  ngOnInit(): void {
    this.httpClient.get<any>(this.dataService.baseUrl + '/measurable/active').subscribe({
      next: data => {
        for (let i = 0; i < data.length; i++) {
          let smoothie = new SmoothieChart();

          this.charts.push(new Chart(data[i].id, data[i].name, data[i].unit, smoothie));
        }

        console.debug(this.charts);
      },
      error: error => {
        console.error('Could not load any measurable', error.message);
      }
    })
  }

并在 ngFor 的帮助下在 html 中为冰沙显示一些必要的画布:

<div class="container">
  <div class="row">
    <div class="col-md-6 mx-auto">
      <p>dashboard works!</p>
      <div class="row" *ngFor="let chart of charts">
        <label>{{ chart.name }}({{ chart.unit }})</label>
        <canvas id="{{ chart.id }}" style="width:100%; height:200px" width="1262" height="200"></canvas>
      </div>
    </div>
  </div>
</div>

在此加载过程中,我想在显示画布后对每个元素调用一个函数,该函数将初始化冰沙图以流式传输数据。 我不能使用ngAfterViewinit 函数,因为API 调用是异步的,它在请求返回数据之前执行。 我在somesimilarposts 中读到它,我可以创建一个指令来执行此操作,但很可能是由于缺乏角度知识,我无法理解和复制它(意思是:我明白了后面也复制了所有的代码,但都没有用)

谁能告诉我如何解决这个问题并解释其背后的逻辑,以便像我这样没有经验的人也能理解它?

【问题讨论】:

    标签: angular typescript callback ngfor


    【解决方案1】:

    在 Angular 中创建一个指令,例如:-

    @Directive({
      selector: '[refresh]'
    })
    export class RefreshDirective implements OnInit {
      @Output() init = new EventEmitter();
      ngOnInit() {
         this.init.emit()
      }
    }
    

    并将您的 html 更改为:-

    <div class="container">
      <div class="row">
        <div class="col-md-6 mx-auto">
          <p>dashboard works!</p>
          <div class="row" *ngFor="let chart of charts">
            <label>{{ chart.name }}({{ chart.unit }})</label>
            <canvas id="{{ chart.id }}" style="width:100%; height:200px" width="1262" height="200" refresh (init) = "myMethod()"></canvas>
          </div>
        </div>
      </div>
    </div>
    

    将 myMethod 更改为您要调用的函数名称,并且不要忘记在模块的声明数组中导入此指令。

    【讨论】:

      猜你喜欢
      • 2016-09-02
      • 1970-01-01
      • 2019-05-16
      • 2020-04-11
      • 1970-01-01
      • 2020-05-02
      • 2021-02-28
      • 2023-03-23
      相关资源
      最近更新 更多