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

查看:403
本文介绍了获取对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.

推荐答案

<ng-template>未添加到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天全站免登陆