Angular 装饰器之 @viewChild | 更文挑战第3天

272 阅读1分钟

这是我参与11月更文挑战的第3天,活动详情查看:2021最后一次更文挑战

官方文档地址

angular.cn/api/core/Vi…

angular.cn/guide/stati…

元数据属性:

selector - 用于查询的指令类型或名字。

read - 从查询到的元素中读取另一个令牌。

static - 如果为 true,则在变更检测运行之前解析查询结果,如果为 false,则在变更检测之后解析。默认为 false。

作用

在ts中获取组件的引用,可以主动触发引入组件的方法

使用方法

  • 假设有个子组件

子组件ts

import { Component } from "@angular/core";
@Component({
  selector: "son-comp",
  template: `<p>子组件</p>`,
})
export class SonComponent {
    play(){
        console.log("调用了");
    }
};

方法1: 父组件ts中引入子组件

父组件ts

import { Component, viewChild } from "@angular/core";
import { SonComponent } from "./son.component.ts"
@Component({
  selector: "parent-comp",
  template: `<p (click)="click()">点击调用子组件方法</p>`,
})
export class ParentComponent {
    @ViewChild(SonComponent) 
    sonRef: SonComponent;
    
    click(){
        this.sonRef.play();
    }
};

方法2: 父组件html中引入子组件

父组件ts

import { Component, viewChild } from "@angular/core";
import { SonComponent } from "./son.component.ts"
@Component({
  selector: "parent-comp",
  template: `
  <son-comp #son></son-comp>
  <p (click)="click()">点击调用子组件方法</p>
  `,
})
export class ParentComponent {
    @ViewChild("son") 
    sonRef: any;
    
    click(){
        this.sonRef.play();
    }
};

获取子组件的dom

  • 假设有个子组件
@Component({
	selector: 'demo', 
	template: `
    	<ul>
            <li></li>
        </ul>
	`
})
export class xxx {}
  • 父组件想获取到它里面的元素
<demo #demo></demo>
import { ViewChild, ElementRef } from '@angular/core';
export class xxx {
    @ViewChild('demo') demo: ElementRef;
    
    constructor(){
          const parentElement = this.demo.element;
          const firstChild = parentElement.children[0];
          const firstImage = parentElement.querySelector("li");
    }
}

彩蛋

Angular中的extendsimplements有何区别?

  • extends: class A extents B
    新建的class A是B的一个子级,它继承了父级B所有的属性和方法,它也可以覆盖父级B的属性和方法。
  • implements: class A implements B
    新建的class A是B的一个投影,它并不是B的子级,B中定义的所有方法和属性A都得去实现。

更多用法更新于 github