Angular 2 ViewChild & ViewChildren

阅读 Angular 6/RxJS 最新教程,请访问 前端修仙之路

ViewChild

ViewChild 是属性装饰器,用来从模板视图中获取匹配的元素。视图查询在 ngAfterViewInit 钩子函数调用前完成,因此在 ngAfterViewInit 钩子函数中,就能正确获取查询的元素。

@ViewChild 使用模板变量名

import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <h1>Welcome to Angular World</h1>
    <p #greet>Hello {{ name }}</p>
  `,
})
export class AppComponent {
  name: string = 'Semlinker';

  @ViewChild('greet')
  greetDiv: ElementRef;

  ngAfterViewInit() {
    console.dir(this.greetDiv);
  }
}

@ViewChild 使用模板变量名及设置查询条件

import { Component, TemplateRef, ViewChild, ViewContainerRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <h1>Welcome to Angular World</h1>
    <template #tpl>
      <span>I am span in template</span>
    </template>
  `,
})
export class AppComponent {

  @ViewChild('tpl')
  tplRef: TemplateRef<any>;

  @ViewChild('tpl', { read: ViewContainerRef })
  tplVcRef: ViewContainerRef;

  ngAfterViewInit() {
    console.dir(this.tplVcRef);
    this.tplVcRef.createEmbeddedView(this.tplRef);
  }
}

@ViewChild 使用类型查询

child.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'exe-child',
    template: `
      <p>Child Component</p>  
    `
})
export class ChildComponent {
    name: string = 'child-component';
}

app.component.ts

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'my-app',
  template: `
    <h4>Welcome to Angular World</h4>
    <exe-child></exe-child>
  `,
})
export class AppComponent {

  @ViewChild(ChildComponent)
  childCmp: ChildComponent;

  ngAfterViewInit() {
    console.dir(this.childCmp);
  }
}

以上代码运行后,控制台的输出结果:

图片描述

ViewChildren

ViewChildren 用来从模板视图中获取匹配的多个元素,返回的结果是一个 QueryList 集合。

@ViewChildren 使用类型查询

import { Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'my-app',
  template: `
    <h4>Welcome to Angular World</h4>
    <exe-child></exe-child>
    <exe-child></exe-child>
  `,
})
export class AppComponent {

  @ViewChildren(ChildComponent)
  childCmps: QueryList<ChildComponent>;

  ngAfterViewInit() {
    console.dir(this.childCmps);
  }
}

以上代码运行后,控制台的输出结果:

图片描述

ViewChild 详解

@ViewChild 示例

import { Component, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <h1>Welcome to Angular World</h1>
    <p #greet>Hello {{ name }}</p>
  `,
})
export class AppComponent {
  name: string = 'Semlinker';
  @ViewChild('greet')
  greetDiv: ElementRef;
}

编译后的 ES5 代码片段

var core_1 = require('@angular/core');

var AppComponent = (function () {
    function AppComponent() {
        this.name = 'Semlinker';
    }
    __decorate([
        core_1.ViewChild('greet'), // 设定selector为模板变量名
        __metadata('design:type', core_1.ElementRef)
], AppComponent.prototype, "greetDiv", void 0);

ViewChildDecorator 接口

export interface ViewChildDecorator {
  // Type类型:@ViewChild(ChildComponent)
  // string类型:@ViewChild('tpl', { read: ViewContainerRef })
  (selector: Type<any>|Function|string, {read}?: {read?: any}): any;

  new (selector: Type<any>|Function|string, 
      {read}?: {read?: any}): ViewChild;
}

ViewChildDecorator

export const ViewChild: ViewChildDecorator = makePropDecorator(
    'ViewChild',
    [
      ['selector', undefined],
      {
        first: true,
        isViewQuery: true,
        descendants: true,
        read: undefined,
      }
    ],
Query);

makePropDecorator函数片段

/*
 * 创建PropDecorator工厂
 * 
 * 调用 makePropDecorator('ViewChild', [...]) 后返回ParamDecoratorFactory
 */
function makePropDecorator(name, props, parentClass) {
          // name: 'ViewChild'
          // props: [['selector', undefined], 
          //  { first: true, isViewQuery: true, descendants: true, read: undefined}]
  
          // 创建Metadata构造函数
        var metaCtor = makeMetadataCtor(props);
      
        function PropDecoratorFactory() {
            var args = [];
               ... // 转换arguments对象成args数组
            if (this instanceof PropDecoratorFactory) {
                metaCtor.apply(this, args);
                return this;
            }
            ...
            return function PropDecorator(target, name) {
                var meta = Reflect.getOwnMetadata('propMetadata', 
                    target.constructor) || {};
                meta[name] = meta.hasOwnProperty(name) && meta[name] || [];
                meta[name].unshift(decoratorInstance);
                Reflect.defineMetadata('propMetadata', meta, target.constructor);
            };
            var _a;
        }
           if (parentClass) { // parentClass: Query
            PropDecoratorFactory.prototype = Object.create(parentClass.prototype);
        }
          ...
        return PropDecoratorFactory;
    }

makeMetadataCtor 函数:

// 生成Metadata构造函数: var metaCtor = makeMetadataCtor(props); 
// props: [['selector', undefined], 
// { first: true, isViewQuery: true, descendants: true, read: undefined }]
  function makeMetadataCtor(props) {
        // metaCtor.apply(this, args);
        return function ctor() {
            var _this = this;
            var args = [];
            ... // 转换arguments对象成args数组
            props.forEach(function (prop, i) { // prop: ['selector', undefined]
                var argVal = args[i]; 
                if (Array.isArray(prop)) { // argVal: 'greet'
                    _this[prop[0]] = argVal === undefined ? prop[1] : argVal;
                }
                else {
             // { first: true, isViewQuery: true, descendants: true, read: undefined }
             // 合并用户参数与默认参数,设置read属性值     
                    for (var propName in prop) { 
                        _this[propName] = 
                            argVal && argVal.hasOwnProperty(propName) ? 
                          argVal[propName] : prop[propName];
                    }
                }
            });
        };
}

我们可以在控制台输入 window['__core-js_shared__'] ,查看通过 Reflect API 保存后的metadata信息

图片描述

接下来我们看一下编译后的 component.ngfactory.js 代码片段,查询条件 @ViewChild('greet')

图片描述

我们再来看一下前面示例中,编译后 component.ngfactory.js 代码片段,查询条件分别为:

1.@ViewChild('tpl', { read: ViewContainerRef })

图片描述

2.@ViewChild(ChildComponent)

图片描述

通过观察不同查询条件下,编译生成的 component.ngfactory.js 代码片段,我们发现 Angular 在创建 AppComponent 实例后,会自动调用 AppComponent 原型上的 createInternal 方法,才开始创建组件中元素,所以之前我们在构造函数中是获取不到通过 ViewChild 装饰器查询的视图元素。另外,配置的视图查询条件,默认都会创建一个 jit_QueryList 对象,然后根据 read 查询条件,创建对应的实例对象,然后添加至 QueryList 对象中,然后在导出对应的查询元素到组件对应的属性中。

总结

ViewChild 装饰器用于获取模板视图中的元素,它支持 Type 类型或 string 类型的选择器,同时支持设置 read 查询条件,以获取不同类型的实例。而 ViewChildren 装饰器是用来从模板视图中获取匹配的多个元素,返回的结果是一个 QueryList 集合。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Angular 中,我们可以通过 `@ViewChild` 或 `@ViewChildren` 装饰器来获取子组件实例。这两个装饰器的区别在于,`@ViewChild` 获取单个子组件实例,而 `@ViewChildren` 获取多个子组件实例。 以下是 `@ViewChild` 的使用方法: ```typescript import { Component, ViewChild } from '@angular/core'; import { ChildComponent } from './child.component'; @Component({ selector: 'app-parent', template: ` <app-child></app-child> <button (click)="logChildComponent()">Log Child Component</button> ` }) export class ParentComponent { @ViewChild(ChildComponent) childComponent: ChildComponent; logChildComponent() { console.log(this.childComponent); } } ``` 在上面的示例中,我们通过 `@ViewChild` 装饰器获取了 `ChildComponent` 的实例,并将其赋值给了 `childComponent` 属性。在 `logChildComponent()` 方法中,我们可以打印出 `ChildComponent` 的实例。 以下是 `@ViewChildren` 的使用方法: ```typescript import { Component, ViewChildren, QueryList } from '@angular/core'; import { ChildComponent } from './child.component'; @Component({ selector: 'app-parent', template: ` <app-child *ngFor="let i of [1, 2, 3]"></app-child> <button (click)="logChildComponents()">Log Child Components</button> ` }) export class ParentComponent { @ViewChildren(ChildComponent) childComponents: QueryList<ChildComponent>; logChildComponents() { console.log(this.childComponents.toArray()); } } ``` 在上面的示例中,我们通过 `@ViewChildren` 装饰器获取了所有 `ChildComponent` 的实例,并将其赋值给了 `childComponents` 属性。在 `logChildComponents()` 方法中,我们可以打印出所有 `ChildComponent` 的实例。需要注意的是,`@ViewChildren` 装饰器返回的是 `QueryList` 对象,需要通过 `toArray()` 方法将其转换为数组。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值