在Angular 2中从父级调用子容器中的函数

Jos*_*ard 3 angular

我目前正在开发一个Angular 2应用程序,我正在尝试在子组件中调用一个函数,但似乎没有任何地方.

我的父组件如下所示:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

和子组件看起来像这样:

注意,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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在理想的世界中,我想drawImage<note-canvas></note-canvas>组件中调用该函数(这是一个将画布绘制到画布的HTML画布).

我可以将pressed属性传递给组件而没有任何问题,但无法找到有关如何执行函数的任何文档.

Gün*_*uer 6

在父级中添加一个字段

@ViewChild(NoteCanvasComponent) noteCanvas: NoteCanvasComponent;
Run Code Online (Sandbox Code Playgroud)

(初始化后ngAfterViewInit).

然后很容易调用它上面的方法

keyPressed(noteData) {
    console.log(noteData); // {key: 30, keyType: "white"}
    this.pressed = noteData;
    noteCanvas.drawImage();
}
Run Code Online (Sandbox Code Playgroud)

  • 这样做了!谢谢你,让我挠了一下头. (2认同)