Angular5 父组件获取子组件实例( ViewChildren、ViewChild用法)
时间: 2023-07-16 12:15:53 浏览: 45
在 Angular 中,我们可以通过 `@ViewChild` 或 `@ViewChildren` 装饰器来获取子组件实例。这两个装饰器的区别在于,`@ViewChild` 获取单个子组件实例,而 `@ViewChildren` 获取多个子组件实例。
以下是 `@ViewChild` 的使用方法:
```typescript
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
<app-child></app-child>
<button (click)="logChildComponent()">Log Child Component</button>
`
})
export class ParentComponent {
@ViewChild(ChildComponent) childComponent: ChildComponent;
logChildComponent() {
console.log(this.childComponent);
}
}
```
在上面的示例中,我们通过 `@ViewChild` 装饰器获取了 `ChildComponent` 的实例,并将其赋值给了 `childComponent` 属性。在 `logChildComponent()` 方法中,我们可以打印出 `ChildComponent` 的实例。
以下是 `@ViewChildren` 的使用方法:
```typescript
import { Component, ViewChildren, QueryList } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
<app-child *ngFor="let i of [1, 2, 3]"></app-child>
<button (click)="logChildComponents()">Log Child Components</button>
`
})
export class ParentComponent {
@ViewChildren(ChildComponent) childComponents: QueryList<ChildComponent>;
logChildComponents() {
console.log(this.childComponents.toArray());
}
}
```
在上面的示例中,我们通过 `@ViewChildren` 装饰器获取了所有 `ChildComponent` 的实例,并将其赋值给了 `childComponents` 属性。在 `logChildComponents()` 方法中,我们可以打印出所有 `ChildComponent` 的实例。需要注意的是,`@ViewChildren` 装饰器返回的是 `QueryList` 对象,需要通过 `toArray()` 方法将其转换为数组。