获取对 ng-template 中元素的引用 [英] Get reference to element inside ng-template

查看:40
本文介绍了获取对 ng-template 中元素的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的模板:

<ng-template #template>
    <input #newimg  type="file" class="col-md-10" (change)="fileChange($event)"/>
</ng-template>

当它在 ng-template 内部时,我无法获得对 #newimg 的引用(如果我将 ng-template 更改为 div!)

I cant get reference to #newimg when its inside ng-template(it works fine if i change ng-template to div!)

@ViewChild('newimg') img: ElementRef; //doesnt work

我需要在上传图片后将其值设置为空,但始终未定义.

I need to set its value to empty after image uploaded but its always undefined.

推荐答案

没有添加到 DOM 中,它只存在于 JavaScript 代码中,当应用程序运行时.只有当它使用例如像 *ngFor*ngIf 这样的结构指令进行标记时,内容才实际在 DOM 和绑定、组件、指令等中创建.被实例化.

<ng-template> is not added to the DOM, it exists only in JavaScript code, when the Application runs. Only when it is stamped using for example a structural directive like *ngFor or *ngIf, the content is actually created in the DOM and bindings, components, directives, ... are instantiated.

因此没有盖章,就没有任何#template可以查询.

Therefore without stamping, there won't be any #template to query for.

这篇关于获取对 ng-template 中元素的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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