ElementRef & TemplateRef & ViewContainerRef

今天在做ng项目,看着前人的代码有 viewChild() 等关键字。新手有点疑惑,索性查查资料总结一下和ng相关的几个和DOM相关的几个概念

ElementRef

由于ng是跨平台的为了减少视图层和渲染层的耦合也为了让ng更适应多平台,ng帮我们封装了ElementRef,我们可以通过ElementRef拿到native元素(在浏览器中也就是我们常说的DOM元素)

下面我们看一段代码

    import { Component, ElementRef, AfterViewInit }  from '@angular/core';
    @Component ({
          selector:'my-app',
          template:`
              
Hello 哇牛!
` }) export class AppComponent(){ @ViewChild('greet') greetDiv: ElementRef construcor(private elementRef: ElementRef, private renderer: Renderer) { } ngAfterViewInit() { // 1: 这一种可以减少耦合,并且做到跨平台 this.renderer.setElementStyle(this.greetDiv.nativeElement, 'backgroundColor',red) // 2: 这一种写法不提倡 this.greetDiv.nativeElement.backgroundColor='red' } }

TemplateRef && ViewContainerRef

template本身是HTML的标签,用于保存客户端的内容机制,该内容在页面渲染时不被加载,但是可以在运行时被javascript解析,详情可以看 Template HTML
TemplateRef

    // @angular/core/src/linker/template_ref.d.ts
    // 用于表示内嵌的template模板,能够用于创建内嵌视(EmbeddedViews)
    export declare abstract class TemplateRef {
        elementRef: ElementRef;
        abstract createEmbeddedView(context: C): EmbeddedViewRef;
    }

templateRef 下面有个抽象方法,不能直接实例化抽象类应该实例抽象化类的子类,每个实例都具有createEmbeddedView方法

ViewContainerRef

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

@Component({
  selector: 'my-app',
  template: `
    

Welcome to Angular World

`, }) export class AppComponent { name: string = 'Semlinker'; @ViewChild('tpl') tplRef: TemplateRef; @ViewChild('tpl', { read: ViewContainerRef }) tplVcRef: ViewContainerRef; ngAfterViewInit() { // console.dir(this.tplVcRef); (1) this.tplVcRef.createEmbeddedView(this.tplRef); } }

TemplateRef:用于表示内嵌的 template 模板元素,通过 TemplateRef 实例,我们可以方便创建内嵌视图(Embedded Views),且可以轻松地访问到通过 ElementRef 封装后的 nativeElement。需要注意的是组件视图中的 template 模板元素,经过渲染后会被替换成 comment 元素。

ViewContainerRef:用于表示一个视图容器,可添加一个或多个视图。通过 ViewContainer
Ref 实例,我们可以基于 TemplateRef 实例创建内嵌视图,并能指定内嵌视图的插入位置,也可以方便对视图容器中已有的视图进行管理。简而言之,ViewContainerRef 的主要作用是创建和管理内嵌视图或组件视图。

你可能感兴趣的:(ElementRef & TemplateRef & ViewContainerRef)