templateref html内容,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

I am span in template

`,

})

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值