angular项目调用子组件方法
时间: 2023-11-29 09:42:19 浏览: 146
Angular父组件调用子组件的方法
在 Angular 中,可以通过 ViewChild 装饰器来获取子组件实例,并调用其方法。具体步骤如下:
1. 在父组件中使用 ViewChild 装饰器获取子组件实例,例如:
```
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
<app-child></app-child>
`
})
export class ParentComponent {
@ViewChild(ChildComponent) childComponent: ChildComponent;
callChildMethod() {
this.childComponent.childMethod();
}
}
```
2. 在子组件中定义需要调用的方法,例如:
```
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<p>Child Component</p>
`
})
export class ChildComponent {
childMethod() {
console.log('Child Method Called');
}
}
```
3. 在父组件中调用子组件的方法,例如:
```
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
<app-child></app-child>
<button (click)="callChildMethod()">Call Child Method</button>
`
})
export class ParentComponent {
@ViewChild(ChildComponent) childComponent: ChildComponent;
callChildMethod() {
this.childComponent.childMethod();
}
}
```
阅读全文