Angular ViewChild fileInput注释未定义 [英] Angular ViewChild fileInput annotation is undefined

查看:113
本文介绍了Angular ViewChild fileInput注释未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的fileInput元素位于普通div中,则可以正常工作.但是,如果我将其放置在<ng-template></ng-template>内,那么它将变得不确定.

If my fileInput element is in a normal div, then it works fine. But if I place it inside <ng-template></ng-template> then I am getting it undefined.

这是我的代码:

HTML

<ng-template #content let-c="close" let-d="dismiss">
   <div class="modal-header">
      <h4 class="modal-title">Modal title</h4>
      <button type="button" class="close" aria-label="Close" (click)="d('Cross click')"></button>
   </div>
   <div class="modal-body">
      <form #documentsForm="ngForm" (ngSubmit)="onEditSubscriberDocumentsSubmit(documentsForm.value);documentsForm.reset()">
         <input #fileInput type="file" #select name="document" [(ngModel)]="document" (click)="onDocUpload()" />       
         <input type="submit" value="Save" class="btn btn-success" [hidden]="addDocHidden">
      </form>
   </div>
   <div class="modal-footer">
      <button type="button" class="btn btn-outline-dark" (click)="c('Close click')">Close</button>
   </div>
</ng-template>

TS

import { Component, OnInit, ViewChild , ElementRef} from '@angular/core';

export class EditSubscriberComponent {
    constructor(private http: Http, private route: ActivatedRoute, private router: Router, private modalService: NgbModal) { }
    @ViewChild("fileInput") fileInput: ElementRef;
    ngOnInit() {
       console.log(this.fileInput)
       // This is undefined. If I place the <input #fileInput type="file"> 
       // in the main div,not under ng-template, then I am getting the 
       // desired output
    }
}

请提出如何从ng-template访问ViewChild

Please suggest how can I access ViewChild from ng-template

推荐答案

您可以使用setter:

You can either use setter:

@ViewChild("fileInput") 
set fileInput(val: ElementRef) {
  if(val) {
    console.log(val);
  }
}

或订阅@ViewChildren更改:

@ViewChildren("fileInput") fileInputs: QueryList<ElementRef>;

ngAfterViewInit() {
  this.fileInputs.changes.subscribe(x => {
    if(x.length) {
      console.log(x[0]);
    }
  })
}

或者如果您确切知道模板何时初始化,则只需使用@ViewChild

or if you know exactly when your template is initialized then just use @ViewChild

@ViewChild("fileInput") fileInput: ElementRef;

...
this.vcRef.createEmbeddedView(this.template); // pseudo code
console.log(this.fileInput);

这篇关于Angular ViewChild fileInput注释未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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