在角2调用子容器功能从父 [英] Calling function in child container from parent in Angular 2
问题描述
我目前工作的一个角2应用程序,我想打电话给一个子组件中的一个功能,但似乎并没有在任何地方获得。
I'm currently working on an Angular 2 app and I'm trying to call a function within a child component but don't appear to be getting anywhere.
我的父组件是这样的:
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;
}
}
和子组件看起来是这样的:
And child component looks like this:
注意-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
功能&LT;注意帆布&GT;&LT; /笔记帆布&GT;
组件(这是一个HTML画布,将绘制图像画布)。
In an ideal world I'd like to call the drawImage
function within the <note-canvas></note-canvas>
component (which is an HTML canvas that will draw an image to the canvas).
我可以在 pressed
属性传递到组件没有任何问题,但无法找到如何执行功能的任何文档。
I can pass the pressed
property into the component without any issues but can't find any documentation on how to execute a function.
推荐答案
在父添加一个字段如
@ViewChild(NoteCanvasComponent) noteCanvas: NoteCanvasComponent;
(初始化后 ngAfterViewInit
)。
然后可以很容易地调用一个方法就可以了。
Then it's easy to call a method on it
keyPressed(noteData) {
console.log(noteData); // {key: 30, keyType: "white"}
this.pressed = noteData;
noteCanvas.drawImage();
}
这篇关于在角2调用子容器功能从父的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!