Angular ViewChild fileInput annotation is undefined

匿名 (未验证) 提交于 2019-12-03 01:08:02

问题:

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.

Here is my code :

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     } } 

Please suggest how can I access ViewChild from ng-template

回答1:

You can either use setter:

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

or subscribe on @ViewChildren changes:

@ViewChildren("fileInput") fileInputs: QueryList<ElementRef>;  ngAfterViewInit() {   this.fileInputs.changes.subscribe(x => {     if(x.length) {       console.log(x[0]);     }   }) } 

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!