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 集合。

  • 相关阅读:
    Java程序员必知的8大排序
    java提高篇-----理解java的三大特性之封装
    树莓派学习笔记——GPIO功能学习
    SQL 服务没有及时响应启动或控制请求”的解决方法
    http://blog.csdn.net/u011001723/article/details/45621027
    error
    Spring @Conditional注解的使用
    Python [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed 解决方法
    python
    local class incompatible: stream classdesc serialVersionUID = -2897844985684768944, local class serialVersionUID = 7350468743759137184
  • 原文地址:https://www.cnblogs.com/junjun-001/p/13274317.html
Copyright © 2011-2022 走看看