Angular ViewChild 与 ViewChildren 介绍

ViewChild 这个属性在 Angular 是属於很常用的一部份

今天就来了解一下 ViewChild 与 ViewChildren 的差别与使用方式吧!

先做一个子组件

HelloComponent

import { Component, Input } from "@angular/core";

@Component({
  selector: "hello",
  template: `<h1>Hello {{ name }}!</h1>`,
  styles: [
    `
      h1 {
        font-family: Lato;
      }
    `,
  ],
})
export class HelloComponent {
  @Input() name: string;
}

ViewChild

属性装饰器,用於配置一个检视查询。 变更检测器会在检视的 DOM 中查询能匹配上该选择器的第一个元素或指令。 如果检视的 DOM 发生了变化,出现了匹配该选择器的新的子节点,该属性就会被更新。
它支援 Type 类型或 string 类型的选择器,同时支持设置 read 查询条件,以获取不同类型的实例。比如 ElementRef 和 ViewContainerRef.

父组件

<hello #hello name="{{ name }}"></hello>
import { AfterViewInit, Component, VERSION, ViewChild } from "@angular/core";
import { HelloComponent } from "./hello.component";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
})
export class AppComponent implements AfterViewInit {
  name = "Angular " + VERSION.major;

  @ViewChild("hello") helloElement: HelloComponent;
  ngAfterViewInit() {
    // child is set
    console.log("helloElement", this.helloElement);
  }
}

console 出来可以直接取到子组件里的变数


ViewChildren

用於配置检视查询的引数装饰器。

父组件

<ng-container *ngFor="let item of arrName">
  <hello #item [name]="item"></hello>
</ng-container>
import { AfterViewInit, Component, VERSION, ViewChild } from "@angular/core";
import { HelloComponent } from "./hello.component";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
})
export class AppComponent implements AfterViewInit {
  arrName = ["aa", "bb", "cc"];
  @ViewChildren("item") itemElement: QueryList<HelloComponent>;

  ngAfterViewInit() {
    this.itemElement.map((e) => {
      console.log("itemElement", e.name); // 依序提出子组件里的值
    });
  }
}

此为 console this.itemElement 的画面

注意:
ViewChildren 一定要搭配 QueryList 一起使用,不然就不能实现列表更新这件事了
因生命周期关系 ViewChildViewChildren 要在 ngAfterViewInit 里才能实现


范例:https://stackblitz.com/edit/angular-ivy-cdn6fp

参考资料:
ViewChild
ViewChildren


<<:  Day19 网页的页首header

>>:  Day18-Webhook 实作(番外篇)LINEBot 之 LINEBotTiny

18. PHPer x API document x Swagger API

想当一个 Good PHPer,不但要写程序、写注解还要写 API 文件,想到要维护三个地方工程师就...

【Day10】Git 版本控制 - 将档案 push 到 GitHub 的懒人包

今天来总结一下该如何将档案从本地数据库 push 到 GitHub 上,写个简单的懒人包,也算再复习...

Jquery/JS 使用Input 输入生日并限制年龄

客户需求如下 不要用datepicker点,说是手机太小不好点+老人不会点 资料库格式为西元年,但一...

Day 20:非 GUI 类工具之 juce::Analytics

为简化使用者行为采集,JUCE 提供了 juce::Analytics 以及相关介面,让开发者依需求...

【Day 12】MySQL Basics

Update(09/28): 已完成 section 4,5 晚上刚回台北QQ 这个笔记还蛮个人的,...