mcpField
A
angular-viewchild

angular-viewchild

github.com/oguzhan18开发7174 次安装31 周前更新
代码仓库

关于 angular-viewchild

面向 Angular 开发者的组件查询参考技能,介绍如何访问元素、投影内容和子组件,以及查询时机与常用选项。

主要功能

  1. 01使用 ViewChild 引用元素
  2. 02使用 ContentChild 获取投影内容
  3. 03设置静态或动态查询时机
  4. 04用 ViewChildren 查询多个元素
  5. 05用 read 选项指定查询令牌
  6. 06访问子组件实例

适用场景

  1. 01在视图初始化后聚焦元素
  2. 02访问组件接收的投影内容
  3. 03获取模板或视图容器
  4. 04遍历匹配的子元素

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/oguzhan18/angular-ecosystem-skills --skill angular-viewchild

安装后在 Claude Code 中输入/angular-viewchild确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/discussions/
_INDEX.md
references/docs/
_INDEX.md
references/issues/
_INDEX.md
references/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