Angular-ViewChild

该指令配置视图查询的属性装饰器,更改检测器在视图dom中查找与选择器匹配的第一个元素或指令。如果视图dom更改,并且新的子项与选择器匹配,则更新属性.
source code:

export interface ViewChildDecorator {
     * Supported selectors include:
     *   * any class with the `@Component` or `@Directive` decorator
     *   * a template reference variable as a string (e.g. query `<my-component #cmp></my-component>`
     * with `@ViewChild('cmp')`)
     *   * any provider defined in the child component tree of the current component (e.g.
     * `@ViewChild(SomeService) someService: SomeService`)
     *   * any provider defined through a string token (e.g. `@ViewChild('someToken') someTokenVal:
     * any`)
     *   * a `TemplateRef` (e.g. query `<ng-template></ng-template>` with `@ViewChild(TemplateRef)
     * template;`)
    (selector: Type<any> | Function | string, opts?: {
        read?: any;
    }): any;
    new (selector: Type<any> | Function | string, opts?: {read?: any;}): ViewChild;
}

在调用NgAfterViewInit回调函数之前就会设置这些视图查询。
元数据属性
【selector】- 用于查询的指令类型或名字。
【read】- 从查询到的元素中读取另一个令牌。
【static】-是否在运行更改检测之前解析查询结果(即仅返回静态结果)。如果不提供此选项,编译器将返回其默认行为,即使用查询结果来确定查询解析的时间。如果任何查询结果位于嵌套视图(例如*ngif)中,则将在运行更改检测之后解析该查询。否则,将在运行更改检测之前解决此问题。

所支持的选择器包括:

  1. 任何带有 @Component 或 @Directive 装饰器的类
  2. 字符串形式的模板引用变量(比如可以使用 @ViewChild(‘cmp’) 来查询 <my-component #cmp></my-component>
  3. 组件树中任何当前组件的子组件所定义的提供商(比如 @ViewChild(SomeService) someService: SomeService )
  4. 任何通过字符串令牌定义的提供商(比如 @ViewChild(‘someToken’) someTokenVal: any )
  5. TemplateRef(比如可以用 @ViewChild(TemplateRef) template; 来查询 <ng-template></ng-template>

用法一:字符串形式的模板引用变量

@ViewChild('ContentElement') mainContent: ElementRef;
在用原生JS中,我们取一个dom元素,使用document.getElementById(‘元素ID’),在NG中用nativeElement来获取一个dom元素对象
HTML:

### <div id="divContent" #ContentElement>
  【divContent】:dom元素id
  【#TempContent】:a template reference variable as a string,字符串的模板、doc元素变量
</div>

TS:

export class AngularViewchildComponent implements OnInit, AfterContentInit {
  @ViewChild('ContentElement') mainContent: ElementRef;
  constructor() { }
  ngOnInit() {
    console.dir(this.mainContent.nativeElement);
    console.dir(document.getElementById('divContent'));
  }
  ngAfterContentInit(): void {
  }
}

监控结果:

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理