zoukankan      html  css  js  c++  java
  • Angular2+ ViewChild & ViewChildren解析

    ViewChild

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

    @ViewChild 通过模板变量名获取DOM元素

    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.log(this.greetDiv.nativeElement);
      }
    }

    @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.log(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装饰器用于获取模板视图中的元素,它支持 Type 类型或 string 类型的选择器。 
        `ViewChildren装饰器是用来从模板视图中获取匹配的多个元素,返回的结果是一个 QueryList 集合。

  • 相关阅读:
    2016/1/24 笔记 集合类 异常
    2016/1/22 3,将id为005的对象从集合中移除
    2016/1/22 1, 1-100 放集合 特定对象移除 2,List集合和Set集合是否可以重复添加
    2016/1/21 练习 arraylist 1,添加 add() 2,遍历集合
    2016/1/21 练习 创建 接口interface 应用implements 类class 并实例化调用
    2016/1/21 解读泛型
    2016/1/20 笔记 1, 包 引入 static 已经补充到类里 2,继承
    2016/1/20 总结构建子类对象时的顺序
    2016/1/20 继承作业
    笔记练习
  • 原文地址:https://www.cnblogs.com/junjun-001/p/13274317.html
Copyright © 2011-2022 走看看