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

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

子组件看起来像这样:

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 Canvas ,它将在 Canvas 上绘制图像)。

我可以通过 pressed属性进入组件没有任何问题,但找不到任何关于如何执行功能的文档。

最佳答案

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

@ViewChild(NoteCanvasComponent) noteCanvas: NoteCanvasComponent;

(在 ngAfterViewInit 之后初始化)。

然后调用方法就很简单了

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

关于angular - 在 Angular 2 中从父容器调用子容器中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34846048/

相关文章:

Angular 2 - 无法使用 URL 直接导航到路由

node.js - 如何在Electron App中调用C# dll方法?

angular - 在带有 TypeScript 的 Ionic 2 中使用第三方 cordova 插件

angular - 在 Angular2 中将 jquery-steps 与 FormGroup 结合使用

javascript - Angular Firestore : Check if data exist and update a global variable based on that

javascript - 使用 webpack 无法让 Angular 组件在项目中工作?

sqlite - Angular 2/ ionic 2 : Save Image from gallery and send as attachment via mailto

json - Angular 6 - 解析 JSON

angular - 获取项目的长度 ngFor async/Observable<Aviso[]>;

javascript - Angular 2 : Emit events across multiple components, 不仅仅是直接父级