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

2024-02-02

我目前正在开发 Angular 2 应用程序,并尝试在子组件中调用函数,但似乎没有任何进展。

我的父组件如下所示:

应用程序组件.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;
    }
}

子组件如下所示:

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;
    }
}

在一个理想的世界里,我想称之为drawImage内的函数<note-canvas></note-canvas>组件(这是一个 HTML 画布,它将在画布上绘制图像)。

我可以通过pressed属性添加到组件中没有任何问题,但找不到任何有关如何执行函数的文档。


在父级中添加一个字段,例如

@ViewChild(NoteCanvasComponent) noteCanvas: NoteCanvasComponent;

(初始化之后ngAfterViewInit).

然后调用它的方法就很容易了

keyPressed(noteData) {
    console.log(noteData); // {key: 30, keyType: "white"}
    this.pressed = noteData;
    noteCanvas.drawImage();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 2中从父容器调用子容器中的函数 的相关文章

随机推荐