angular中的@ViewChild
时间: 2025-07-05 17:08:13 浏览: 14
### Angular 中 `@ViewChild` 的使用方法
#### 获取组件或指令引用
`@ViewChild` 装饰器允许父组件获取其视图内定义的子组件或指令的实例。这可以通过指定目标的选择器来完成,可以是类型、字符串或其他。
```typescript
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child/child.component';
@Component({
selector: 'app-parent',
template: `<app-child #childRef></app-child>`
})
export class ParentComponent implements AfterViewInit {
@ViewChild('childRef') child!: ChildComponent;
ngAfterViewInit() {
console.log(this.child); // 访问到子组件实例
}
}
```
上述代码展示了如何通过模板变量名 `#childRef` 来选取子组件,并将其赋给 `ParentComponent` 类中的 `child` 属性,在生命周期钩子 `ngAfterViewInit` 后可安全访问此属性[^1]。
#### 使用 ElementRef 操作 DOM 元素
除了获取组件外,还可以利用 `ElementRef` 对象直接操纵 HTML 元素:
```typescript
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `<button #myButton>Click me</button>`
})
export class AppComponent implements AfterViewInit {
@ViewChild('myButton', { read: ElementRef }) button!: ElementRef;
ngAfterViewInit() {
this.button.nativeElement.style.backgroundColor = 'lightblue';
}
}
```
这里设置了 `{ read: ElementRef }` 参数告诉 Angular 返回的是一个 `ElementRef` 实例而不是默认的行为。接着可以在 `ngAfterViewInit` 方法里修改按钮样式[^4]。
#### Static vs Dynamic 查询模式
当声明 `@ViewChild` 时可以选择静态还是动态查询方式,取决于是否设置 `static` 参数为 `true` 或者保持默认值 `false`:
- 当 `static=true` ,表示希望在首次渲染前就获得元素;
- 默认情况下 (`static=false`) 则是在整个视图构建完成后才可用这些元素。
对于上面提到的例子来说,如果想要尽早拿到子组件,则应如此编写:
```typescript
@ViewChild(ChildComponent, { static: true })
private childComp!: ChildComponent;
```
而如果是基于事件或者其他逻辑条件加载的内容则应该保留默认配置[^3]。
阅读全文
相关推荐


















