Angular ElementRef、TemplateRef、viewContainerRef 的区别

今天就来聊聊 ElementRefTemplateRefviewContainerRef,者实说,在这之前一直都没很认真搞懂这部份
就趁着这次机会一起来看看吧!

ElementRef

用於检视 HTML DOM 元素,可以在浏览器中取得 DOM 的原生 Element

ElementRef

.html

<span #elRef>I am span</span>

.ts

export class TemplateComponent implements AfterViewInit {
  @ViewChild("elRef") elRef!: ElementRef;

  ngAfterViewInit() {
    console.log("ElementRef", this.elRef.nativeElement.textContent); //I am span
  }
}

TemplateRef

属於模板元素的一种,在页面里不会呈现,但可透过 ViewContainerRef 将它渲染出来

.html

<ng-template #tpRef><span>I am span in template</span></ng-template>

.ts

export class TemplateComponent implements AfterViewInit {
  @ViewChild('tpRef') tplRef!: TemplateRef<any>;

  ngAfterViewInit() {
    console.log("TemplateRef", this.tplRef.elementRef.nativeElement); //<!--container-->
    console.log("TemplateRef", this.tplRef.elementRef.textContent); //container
  }
}

这里可以看到 把 TemplateRef console 出来会是一个 container,在 html 上是就只是一个注解。


viewContainerRef

它用来操控显示的内容
有着 host 与 embedded view 来建立动态显示

接续着刚刚的 TemplateRef

.html

<span>I am first span</span>
<ng-container #vc></ng-container>
<span>I am last span</span>

<ng-template #tpRef
  ><span style="color:red;">I am span in template</span></ng-template
>

<!-- 加两颗按钮,试着操控 TemplateRef -->
<button (click)="onRemoveTpl()">removeTpl</button>
<button (click)="onAddTpl()">addTpl</button>

.ts

export class TemplateComponent implements AfterViewInit {
  @ViewChild('tpRef') tplRef!: TemplateRef<any>;

  ngAfterViewInit() {
    const elem = this.tplRef.createEmbeddedView(null);
    this.vc.insert(elem);
  }

  onRemoveTpl() {
    this.vc.remove();
  }

  onAddTpl() {
    this.vc.createEmbeddedView(this.tplRef);
  }
}

试着玩玩看范例吧!

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


参考资料:

Exploring Angular DOM manipulation techniques using ViewContainerRef

Angular 2 TemplateRef & ViewContainerRef


<<:  DAY 16 『 改用 xib 进行界面创作 』

>>:  【Day 28】JavaScript Promise

Day-03 Regression & Gradient Descent 介绍

我们昨天聊过了到底如何做机器学习,且也知道机器学习的核心概念是取得所谓的最佳 function,回...

Day 07 - Spring Boot 常用依赖

正如Day 04 - Spring Boot 的前世今生所说,Spring Boot 为了简化设定提...

DAY11:应用程序元件Activity之实作

今天,我要做个简单的小程序,实作前一天所介绍到的Activity功能。我要做的是关於牛排馆的点餐系统...

DAY 28:Command Pattern,将动作已指令一个一个完成

什麽是 Command Pattern? 将建立指令与实际执行分离 问题情境 PS5 有特定操作 C...