Call function in child container from parent in Angular 2

I am currently working on an Angular 2 application, and I am trying to call a function in a child component, but it seems to be there.

My parent component is as follows:

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 the child component is as follows:

notebook 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 would like to call a function drawImagein a component <note-canvas></note-canvas>(which is an HTML canvas that will draw an image on the canvas).

I can pass the property pressedto the component without any problems, but I can not find the documentation on how to execute the function.

+3
source share
1 answer

In the parent add a type field

@ViewChild(NoteCanvasComponent) noteCanvas: NoteCanvasComponent;

( ngAfterViewInit).

keyPressed(noteData) {
    console.log(noteData); // {key: 30, keyType: "white"}
    this.pressed = noteData;
    noteCanvas.drawImage();
}
+6

Source: https://habr.com/ru/post/1624755/


All Articles