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.

1
  • Try something like this... Commented Jan 18, 2016 at 3:04

1 Answer 1

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

That did the job! Thanks for that, had me scratching my head for a while.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.