Angular ViewChild fileInput 注释未定义

Adr*_*rma 2 typescript angularjs-ng-template ng-template viewchild angular

如果我的 fileInput 元素位于普通 div 中,那么它可以正常工作。但如果我把它放在里面<ng-template></ng-template>那么我就会得到它的未定义。

这是我的代码:

超文本标记语言

<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>
Run Code Online (Sandbox Code Playgroud)

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
    }
}
Run Code Online (Sandbox Code Playgroud)

请建议我如何从 ng-template 访问 ViewChild

yur*_*zui 6

您可以使用设置器:

@ViewChild("fileInput") 
set fileInput(val: ElementRef) {
  if(val) {
    console.log(val);
  }
}
Run Code Online (Sandbox Code Playgroud)

或订阅@ViewChildren更改:

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

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

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

@ViewChild("fileInput") fileInput: ElementRef;

...
this.vcRef.createEmbeddedView(this.template); // pseudo code
console.log(this.fileInput);
Run Code Online (Sandbox Code Playgroud)