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

情到浓时终转凉″ 提交于 2019-12-20 03:21:07

问题


Currently I'm working in a view where I have to dynamically create HTML elements.

I'm creating the HTML elements with *ngFor directive bounded with an Array.

I need to refer the new HTML element with JQuery selector after push a new object into the Array, but the HTML element is not rendered yet.

How can I trigger a function just after the HTML element is ready ?

Thanks in advance.


回答1:


You can follow below steps inside the component:-

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.

The whole logic is that ngAfterViewInit() works when the HTML is fully loaded and you have to do something on that HTML. For example your view has some static HTML and some external JS files are creating some HTML elements inside some div dynamically. So first you will load your view using ngOnInit() and then using external JS you can create and bind html elements dynamically to that div.

I hope this helps you.

All the best.




回答2:


As pointed out in the comments, you probably don't want to use JQuery on Angular DOM elements if you have a choice. It will lead to endless confusion.

You can, however, access a component's DOM children using elementRef.nativeElement. The lifecycle hook where you want to run that in the case of *ngFor (or other structural directives) is AfterViewChecked. At that point, you know that the component has finished binding and rendering its content.

Combined, here's a cheap little example just coloring all dynamically generated divs of a component:

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');
  }

}


来源:https://stackoverflow.com/questions/51079111/angular-5-how-to-call-a-function-when-html-element-is-created-with-ngfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!