3

I'm currently working on an Angular 2 app and I'm trying to call a function within a child component but don't appear to be getting anywhere.

My parent component looks like this:

app.component.ts

@Component({
    selector: 'piano-app',
    styleUrls: ['app/components/app/app.component.css'],
    template: `
        <div id="gameWrapper">
            <note-canvas [keyPressed]="pressed"></note-canvas>
            <piano (key-pressed)="keyPressed($event)"></piano>
        </div>
    `,
    directives: [PianoComponent, NoteCanvasComponent],
})
export class AppComponent {

    public pressed: any;

    // This event is successfully called from PianoComponent
    keyPressed(noteData) {
        console.log(noteData); // {key: 30, keyType: "white"}
        this.pressed = noteData;
    }
}

And child component looks like this:

note-canvas.component.ts

export class NoteCanvasComponent implements OnInit {

    ...

    @Input() keyPressed : any;

    constructor(private element: ElementRef, private noteGenerator: NoteFactory) {
        this.canvas = this.element.nativeElement.querySelector('canvas');
        this.context = this.canvas.getContext('2d');
        this.canvasWidth = 900;
        this.noteFactory = noteGenerator;
    }

    public drawImage() {
        // Draw image based on value of keyPressed data;
    }
}

In an ideal world I'd like to call the drawImage function within the <note-canvas></note-canvas> component (which is an HTML canvas that will draw an image to the canvas).

I can pass the pressed property into the component without any issues but can't find any documentation on how to execute a function.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Joseph Woodward
  • 9,191
  • 5
  • 44
  • 63
  • Try something [like this](http://stackoverflow.com/questions/34802210/angular-2-child-component-events-broadcast-to-parent/34807012#34807012)... – Sasxa Jan 18 '16 at 03:04

1 Answers1

6

In the parent add a field like

@ViewChild(NoteCanvasComponent) noteCanvas: NoteCanvasComponent;

(initialization after ngAfterViewInit).

Then it's easy to call a method on it

keyPressed(noteData) {
    console.log(noteData); // {key: 30, keyType: "white"}
    this.pressed = noteData;
    noteCanvas.drawImage();
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567