Angular 5 - 如何在使用 *ngFor 创建 HTML 元素时调用函数 [英] Angular 5 - How to call a function when HTML element is created with *ngFor

查看:27
本文介绍了Angular 5 - 如何在使用 *ngFor 创建 HTML 元素时调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我在一个视图中工作,我必须动态创建 HTML 元素.

我正在使用 *ngFor 指令创建 HTML 元素,并以数组为界.

在将新对象推入数组后,我需要使用 JQuery 选择器引用新的 HTML 元素,但 HTML 元素尚未呈现.

如何在 HTML 元素准备好后立即触发函数?

提前致谢.

解决方案

正如评论中所指出的,如果您有选择,您可能不想在 Angular DOM 元素上使用 JQuery.它会导致无休止的混乱.

但是,您可以使用 elementRef.nativeElement 访问组件的 DOM 子级.在*ngFor(或其他结构指令)的情况下,您想要运行它的生命周期钩子是AfterViewChecked.此时,您就知道该组件已完成绑定并呈现其内容.

结合起来,这是一个简单的小例子,只是为组件的所有动态生成的 div 着色:

import {AfterViewChecked, Component, ElementRef} from '@angular/core';@成分({选择器:'app-root',模板:`<div *ngFor="让条目进入">{{入口}}

`})导出类 AppComponent 实现 AfterViewChecked {构造函数(私有元素引用:元素引用){}条目 = ['a', 'b', 'c'];ngAfterViewChecked(): 无效 {const divs = this.elementRef.nativeElement.querySelectorAll('div');divs.forEach(div => div.style.background = '红色');}}

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.

解决方案

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

}

这篇关于Angular 5 - 如何在使用 *ngFor 创建 HTML 元素时调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆