Angular装饰器ContentChild

5次阅读

共计 2468 个字符,预计需要花费 7 分钟才能阅读完成。

该指令配置视图查询的属性装饰器,更改检测器在视图 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>

用法一:(selector:string)字符串形式的模板引用变量访问元素

@ViewChild('ContentElement') mainContent: ElementRef;
在用原生 JS 中,我们取一个 dom 元素,使用 document.getElementById(‘ 元素 ID’), 在 NG 中用 nativeElement 来获取一个 dom 元素对象, 当我们获取到这个 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 {}
}

监控结果:

用法二:(selector: Type<any>)任何带有 @Component 或 @Directive 装饰器的类访问子组件

html:

<p> 直接获取组件对象:</p>
<app-angular-viewchildcomponent #NChildComponent></app-angular-viewchildcomponent>

TS:

// 直接引入组件:@ViewChild(AngularViewchildcomponentComponent) childComponent: AngularViewchildcomponentComponent;
@ViewChild('NChildComponent') childComponentByName: AngularViewchildcomponentComponent;

ngAfterViewInit() {this.childComponent.changedNameByClass('太阳');
    this.childComponentByName.changedNameByName('月亮');
}

你可以在父组件上操作子组件的方法,使劲盘他,这个和在父页面调用 iframe 对象一样,现在获取到 iframe 对象,不过在实际使用中我还没有看到有多大用处,还是用一个明确的模板引用变量实在点,定位明确。

正文完
 0