关于 angular-viewchild
面向 Angular 开发者的组件查询参考技能,介绍如何访问元素、投影内容和子组件,以及查询时机与常用选项。
主要功能
- 01使用 ViewChild 引用元素
- 02使用 ContentChild 获取投影内容
- 03设置静态或动态查询时机
- 04用 ViewChildren 查询多个元素
- 05用 read 选项指定查询令牌
- 06访问子组件实例
适用场景
- 01在视图初始化后聚焦元素
- 02访问组件接收的投影内容
- 03获取模板或视图容器
- 04遍历匹配的子元素
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ oguzhan18/ angular-ecosystem-skills --skill angular-viewchild安装后在 Claude Code 中输入/angular-viewchild确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/discussions/_INDEX.mdreferences/docs/_INDEX.mdreferences/issues/_INDEX.mdreferences/releases/_INDEX.md详细介绍
Angular ViewChild / ContentChild
版本: Angular 21(2025 年) 标签: ViewChild、ContentChild、DOM、查询
参考: ViewChild API • ContentChild API
最佳实践
- 使用 ViewChild 获取元素引用
import { ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({})
export class MyComponent implements AfterViewInit {
@ViewChild('input') inputEl!: ElementRef<HTMLInputElement>;
ngAfterViewInit() {
this.inputEl.nativeElement.focus();
}
}
- 使用 static 选项
// Static - available in ngOnInit
@ViewChild('static', { static: true }) staticEl!: ElementRef;
// Dynamic - available in ngAfterViewInit
@ViewChild('dynamic', { static: false }) dynamicEl!: ElementRef;
- 使用 ContentChild 获取投影内容
import { ContentChild, TemplateRef } from '@angular/core';
@Component({
selector: 'app-card',
template: `
<div class="card">
<ng-content></ng-content>
</div>
`
})
export class CardComponent {
@ContentChild(TemplateRef) headerTemplate!: TemplateRef<any>;
}
- 使用 ViewChildren 获取多个元素
import { ViewChildren, QueryList } from '@angular/core';
@Component({})
export class ListComponent {
@ViewChildren('item') items!: QueryList<ElementRef>;
ngAfterViewInit() {
this.items.forEach(item => console.log(item));
}
}
- 使用 read 选项
@ViewChild('component', { read: ViewContainerRef }) container!: ViewContainerRef;
@ViewChild('template', { read: TemplateRef }) template!: TemplateRef<any>;
- 访问组件实例
@ViewChild(ChildComponent) child!: ChildComponent;
ngAfterViewInit() {
this.child.doSomething();
}
- 与信号搭配使用
@ViewChild('el') el!: ElementRef<HTMLElement>;
ngAfterViewInit() {
effect(() => {
if (this.shouldFocus()) {
this.el.nativeElement.focus();
}
});
}
评论
支持 Markdown