3

New to angularjs 2, I need to use @viewChild but it throws error as 'Cannot read property 'rotateLeft' of undefined'. parent :

<div><pdfReader [imageUrl]="imgsource" *ngIf="holeDocument.ext == 'pdf'"></pdfReader></div> 

.ts

import { Component ,ViewChild } from '@angular/core';
import {PdfReader} from "../../shared/pdfreader/pdfReader";
@Component({
selector: 'docView',
templateUrl: 'docView.html',
styleUrls : ["docView.less"]
})  
export class DocViewComponent{
@ViewChild('PdfReader') public pdfReader: PdfReader;
constructor(){}
ngAfterViewInit(){
    this.imageRotate();
}             
imageRotate(){ 
this.pdfReader.rotateLeft();
}}

Child :

@Component({
selector: 'pdfReader',
templateUrl: 'pdfReader.html'
})
export class PdfReader{
 @Input() imageUrl : any;
 rotateLeft(){
        console.log('rotateLeft called');
        this.rotationAngel -= 90;
    }
}
sibi
  • 635
  • 3
  • 8
  • 26
  • I can't see in your question how you use `@ViewChild()`. Don't you think this would be the most important part of your question? – Günter Zöchbauer Feb 02 '17 at 13:56
  • @GünterZöchbauer @ViewChild('PdfReader') public pdfReader: PdfReader; also edited. – sibi Feb 02 '17 at 14:01
  • What does `console.log(this.pdfReader);` in `ngAfterViewInit()` print? Is the HTML in your question part of the components template. Please add the `@Component()` decorators and the components class name to the code. – Günter Zöchbauer Feb 02 '17 at 14:05

2 Answers2

2

If you use the component type to query, then the quotes are redundant

@ViewChild(PdfReader) public pdfReader: PdfReader;

If you use a string as query there needs to be a matching template variable

<div><pdfReader #PdfReader [imageUrl]="imgsource" *ngIf="holeDocument.ext == 'pdf'"></pdfReader></div> 

See also angular 2 / typescript : get hold of an element in the template

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
1
 *ngIf="holeDocument.ext == 'pdf'"

*ngIf is doing the trick. element is not rendered until that condition has met.

use [hidden] instead.

<pdfReader [imageUrl]="imgsource" [hidden]="holeDocument.ext != 'pdf'"></pdfReader>
Subindev
  • 148
  • 2
  • 10