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

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

问题描述

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

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

我正在使用带有数组限制的* ngFor指令创建HTML元素.

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

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

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.

如何在HTML元素准备好后立即触发功能?

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

谢谢.

推荐答案

您可以在组件内部执行以下步骤:-

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.

整个逻辑是,当HTML完全加载时ngAfterViewInit()可以工作,并且您必须在该HTML上执行某些操作.例如,您的视图具有一些静态HTML,并且一些外部JS文件正在一些div中动态创建一些HTML元素. 因此,首先您将使用ngOnInit()加载视图,然后使用外部JS来动态创建html元素并将其绑定到该div.

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.

希望对您有帮助.

祝一切顺利.

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

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