Angular中常用Ref总结

1、ApplicationRef

两个主要个作用:

(1)可以通过appRef.tick()来全局性调用变化检测;

   ApplicationRef.tick() - 检查所有组件树

(2)可以将视图用attachView()包含到变化检测中 用detachView()将视图移除变化检测 ;

  不用ViewContainerRef,动态插入一个组件到一个特定的DOM节点:

export class DrawService {
  component: ComponentFactory<DrawComponent>;
  ref: ComponentRef<DrawComponent>;
  promise: Promise<{}>;

  constructor(private resolver: ComponentFactoryResolver,
              private injector: Injector,
              private applicationRef: ApplicationRef) {
  }

  open(data: any){
    if (this.component != null) {
      return;
    }
    this.component = this.resolver.resolveComponentFactory(DrawComponent);
    let node = document.body.insertBefore(document.createElement(this.component.selector), document.body.firstChild);
    this.ref = this.component.create(this.injector, [], node);
    // 用ApplicationRef的attach()方法把这个视图绑定到变化检测。这时候不通过Input和ngOnChanges操作就可以更新DOM了
    this.applicationRef.attachView(this.ref.hostView);
    return instance;
  }
}

2、ComponentRef

表示通过ComponentFactory创建的组件的实例。

ComponentRef提供对组件实例的访问以及与此组件实例相关的其他对象,并允许您通过destroy方法销毁组件实例。

抽象类定义如下:

abstract class ComponentRef<C> {
  abstract location: ElementRef // 组件实例的宿主元素所在的位置
  abstract injector: Injector // 组件实例存在的注射器
  abstract instance: C // 组件实例
  abstract hostView: ViewRef // 组件实例的宿主视图ViewRef
  abstract changeDetectorRef: ChangeDetectorRef // 组件的ChangeDetectorRef
  abstract componentType: Type<any> // 组件类型
  abstract destroy(): void // 销毁组件实例及其附加数据
  abstract onDestroy(callback: Function): void // 允许注册将在组件销毁时调用的回调。
}

3、TemplateRef

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

抽象类定义:

abstract class TemplateRef<C> {
  abstract elementRef: ElementRef
  abstract createEmbeddedView(context: C): EmbeddedViewRef<C>
}

 templateRef创建Embedded Views视图的方法如下:

@ViewChild('tp1') tp1: TemplateRef<any>;
const view = this.tp1.createEmbeddedView(null);

4、ViewContainerRef

用于表示视图容器,可以添加一个或多个视图。ViewContainerRef 实例,我们可以基于 TemplateRef 实例创建内嵌视图,并能指定内嵌视图的插入位置,也可以方便对视图容器中已有的视图进行管理。也就是说,ViewContainerRef 的主要作用是创建和管理内嵌视图(Embedded Views)或组件视图(hostViews)。

ViewContainerRef添加内嵌视图(Embedded Views 通过createEmbeddedView实例化嵌入式模板创建)

@Component({
  selector: 'app-demo-test',
  template: `
    <div style="margin: 30px">
      <div>
        <button id="btn" #btn>click</button>
        <!-- 此处也可以替换为ng-container -->
        <ng-template #container1></ng-template>
      </div>
      <ng-template #tp1>
        <span>
          fasdfasdfasdf
        </span>
      </ng-template>
    </div>
  `,
  styles: [`
    
  `]
})
export class DemoTestComponent implements OnInit {
  @ViewChild('tp1') tp1: TemplateRef<any>;
  @ViewChild('container1', {read: ViewContainerRef}) container: ViewContainerRef;
  constructor() { }

  ngOnInit() {

  }

  ngAfterViewInit() {
    const view = this.tp1.createEmbeddedView("123123");
    this.container.insert(view);
  }
}

ViewContainerRef创建组件视图(Host Views 通过使用createComponent实例化组件创建 ),核心代码如下:

@ViewChild('componentContainer', {read: ViewContainerRef}) container: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) {
  }
open() {
    this.componentRef = this.container.createComponent(this.resolver.resolveComponentFactory(this.injectComponent));
    this.instance = this.componentRef.instance;
}

5、ElementRef

Angular 的口号是 - "一套框架,多种平台,即同时适用手机与桌面。在应用层直接操作 DOM,就会造成应用层与渲染层之间强耦合,导致我们的应用无法运行在不同环境,通过 ElementRef 我们就可以封装不同平台下视图层中的 native 元素 (在浏览器环境中,native 元素通常是指 DOM 元素),最后借助于 Angular 提供的强大的依赖注入特性,我们就可以轻松地访问到 native 元素。

ElementRef定义如下:

class ElementRef<T> {
  constructor(nativeElement: T)
  nativeElement: T
}

ElementRef配合Renderer类使用例子:

import { Component, ElementRef, ViewChild, AfterViewInit, Renderer } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <h1>Welcome to Angular World</h1>
    <div #greet>Hello {{ name }}</div>
  `,
})
export class AppComponent {
  name: string = 'world';

  @ViewChild('greet')
  greetDiv: ElementRef;

  constructor(private elementRef: ElementRef, private renderer: Renderer) { }

  ngAfterViewInit() {
    // this.greetDiv.nativeElement.style.backgroundColor  = 'red';
    this.renderer.setElementStyle(this.greetDiv.nativeElement, 'backgroundColor', 'red');
  }
}

 6、ViewRef

抽象类定义:

abstract class ViewRef extends ChangeDetectorRef {
  abstract destroyed: boolean
  abstract destroy(): void
  abstract onDestroy(callback: Function): any

  // 继承自 core/ChangeDetectorRef
  abstract markForCheck(): void
  abstract detach(): void
  abstract detectChanges(): void
  abstract checkNoChanges(): void
  abstract reattach(): void
}

 ViewRef 用于表示 Angular View(视图),视图是可视化的 UI 界面。EmbeddedViewRef 继承于 ViewRef,用于表示 <template> 模板元素中定义的 UI 元素。

官网API地址:https://angular.cn/api,根据对应的类名或接口名自行搜索。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值