1

fileInput要素が通常のdivにある場合、正常に動作します。しかし、私がそれを<ng-template></ng-template>の中に置くと、私はそれを未定義にしています。ここで角度ViewChild fileInputアノテーションが定義されていません

は私のコードです:

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-テンプレートから目的税のViewChildは

答えて

1

あなたはセッターを使用することができ、次のいずれか

@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); 
+0

ご協力ありがとうございます。あなたはこの行 'this.vcRef.createEmbeddedView(this.template)'を親切に説明できますか?私はAngularでかなり新しいですし、入植者を使用していることは助けにはなりません。 –

+0

どの角度ライブラリを使用していますか?あなたのモーダルが開かれたときにセッターを呼び出す必要があります – yurzui

+0

モーダルにNgbModalを使用しています –

関連する問題