我目前正在开发 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/