要在Angular 6中使用子组件的函数,你可以通过以下步骤来实现:
import { Component } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
Parent Component
`
})
export class ParentComponent {
// 获取对子组件的引用
@ViewChild('child') childComponent: ChildComponent;
// 调用子组件的函数
callChildFunction() {
this.childComponent.childFunction();
}
}
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
template: `
Child Component
`
})
export class ChildComponent {
// 子组件中的函数
childFunction() {
console.log('Child function called');
}
}
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
Parent Component
`
})
export class ParentComponent {
@ViewChild('child') childComponent: ChildComponent;
callChildFunction() {
this.childComponent.childFunction();
}
}
通过以上步骤,你现在可以在父组件中调用子组件的函数。当点击“Call Child Function”按钮时,子组件的函数将被调用,并在控制台中打印一条消息。