在Angular 2

时间:2016-01-18 01:42:37

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

子组件看起来像这样:

注意-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属性传递给组件而不会出现任何问题,但无法找到有关如何执行函数的任何文档。

1 个答案:

答案 0 :(得分:6)

在父级中添加类似

的字段
android:centerInParent="true"

@ViewChild(NoteCanvasComponent) noteCanvas: NoteCanvasComponent; 之后的初始化)。

然后在其上调用方法很容易

ngAfterViewInit