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:`
              <div #greet>Hello  哇牛!</div>
          `
    })
    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<C> {
        elementRef: ElementRef;
        abstract createEmbeddedView(context: C): EmbeddedViewRef<C>;
    }

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

ViewContainerRef

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

@Component({
  selector: 'my-app',
  template: `
    <h1>Welcome to Angular World</h1>
    <template #tpl>
      <span>I am span in template</span>
    </template>
  `,
})
export class AppComponent {
  name: string = 'Semlinker';

  @ViewChild('tpl')
  tplRef: TemplateRef<any>;

  @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 的主要作用是创建和管理内嵌视图或组件视图。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 这篇文章我们将介绍在 Angular 中如何动态创建组件。 定义 AlertComponent 组件 首先,我们需...
    semlinker阅读 1,628评论 0 5
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,947评论 6 342
  • AngularJS AngularJS概述 介绍 简称:ng Angular是一个MVC框架 其他前端框架: Vu...
    我爱开发阅读 2,347评论 0 8
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,179评论 25 708
  • 妈妈,您是美丽的女人!您给了我生命,又抚养我长大成人,我感谢您! 在这世界上,不是生了孩子就是一个好妈妈的,有些...
    静心专注阅读 235评论 3 5