簡體   English   中英

Angular 5-使用* ngFor創建HTML元素時如何調用函數

[英]Angular 5 - How to call a function when HTML element is created with *ngFor

目前,我在必須動態創建HTML元素的視圖中工作。

我正在創建* ngFor指令並以數組為界的HTML元素。

將新對象推入Array后,我需要使用JQuery選擇器引用新的HTML元素,但是HTML元素尚未呈現。

HTML元素准備好后,如何觸發函數?

提前致謝。

您可以在組件內部執行以下步驟:-

1) On ngOnInit(), you can write logic which is responsible for generating dynamic HTML.

2) On ngAfterViewInit(), you can write the logic for the functionality which is responsible to be applied after HTML view is loaded.

整個邏輯是,當HTML完全加載后,ngAfterViewInit()可以工作,並且您必須在該HTML上執行某些操作。 例如,您的視圖具有一些靜態HTML,並且一些外部JS文件正在一些div中動態創建一些HTML元素。 因此,首先您將使用ngOnInit()加載視圖,然后使用外部JS創建動態html元素並將其綁定到該div。

我希望這可以幫助你。

祝一切順利。

正如評論中指出的那樣,如果您願意的話,可能不想在Angular DOM元素上使用JQuery。 這將導致無休止的混亂。

但是,您可以使用elementRef.nativeElement訪問組件的DOM子elementRef.nativeElement 對於*ngFor (或其他結構性指令),要在其上運行的生命周期掛鈎是AfterViewChecked 到那時,您知道該組件已完成綁定並呈現其內容。

結合起來,這是一個廉價的小示例,只為組件的所有動態生成的div着色:

import {AfterViewChecked, Component, ElementRef} from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div *ngFor="let entry of entries">
      {{entry}}
    </div>
  `
})
export class AppComponent implements AfterViewChecked {

  constructor(private elementRef: ElementRef) {}

  entries = ['a', 'b', 'c'];

  ngAfterViewChecked(): void {
    const divs = this.elementRef.nativeElement.querySelectorAll('div');
    divs.forEach(div => div.style.background = 'red');
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM