【问题标题】:Angular ViewChild fileInput annotation is undefinedAngular ViewChild fileInput 注释未定义
【发布时间】:2018-02-25 08:05:46
【问题描述】:

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

这是我的代码:

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

【问题讨论】:

    标签: angular typescript viewchild ng-template angularjs-ng-template


    【解决方案1】:

    你可以使用 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

    @ViewChild("fileInput") fileInput: ElementRef;
    
    ...
    this.vcRef.createEmbeddedView(this.template); // pseudo code
    console.log(this.fileInput);
    

    【讨论】:

    • 感谢您的指导。你能解释一下这条线this.vcRef.createEmbeddedView(this.template)吗?我是 Angular 的新手,使用定居者没有帮助。
    • 您使用的是哪个 Angular 库?打开模式时应该调用 Setter
    • 我将 NgbModal 用于模态
    • ng-bootstrap create template outside component 这就是它不工作的原因
    猜你喜欢
    • 2016-04-29
    • 2018-01-24
    • 2019-06-23
    • 2019-10-19
    • 2017-01-08
    • 2019-07-28
    • 2020-03-25
    • 2017-11-16
    相关资源
    最近更新 更多