如何保存组件的TemplateRef参考?

时间:2018-02-27 13:32:40

标签: angular

拥有组件模板(test.component.ts):

test.component.html

<ng-template #template>
  <p>Content!</p>   
</ng-template>

在test.component.ts中我想引用相应的模板并保存该引用。所以,在组件中:

import { Component, ViewChild, TemplateRef, AfterViewInit } from '@angular/core';
import { TestService } from './test.service';
................................................
export class TestComponent implements AfterViewInit {

  constructor(private TestService: TestService) {}
  @ViewChild('template') template: TemplateRef<any>;

  ngAfterViewInit() {
//here I am trying to save reference for template in service
//reference is saved when AfterViewInit takes place 
        this.TestService.setTemplate(this.template);
      }
}

test.service.ts

import { Injectable, TemplateRef } from '@angular/core';

@Injectable()
export class TestService {
  public templateRef: TemplateRef<any>;

  constructor() {}
//setter-method for saving reference
  setTemplate(template: TemplateRef<any>) {
    this.templateRef = template;
  }

//getter-method for getting reference for corresponding template

  getTemplate() {
    return this.templateRef;
  }
}

在某些时刻,我需要从另一个组件调用一些TestComponent方法并获取相应模板的引用:

   public someMethod() {

    .......................................
//here I am trying to get corresponding reference, but reference is undefined
        let template = this.alertService.getTemplate();
    .........................................

  }

是否可以随时保存对使用它的模板的引用?

1 个答案:

答案 0 :(得分:0)

问题

  

种族条件

当您尝试访问模板参考的第二个组件在创建第一个组件之前构建时,会发生这种情况

解决方案

只有克服竞争条件的方法,即未定义模板参考,才能使用事件发射器。

  

事件发射器

export class TestService {
  public onTemplateRefChange: EventEmitter<any> = new EventEmitter<any>();
  public templateRef: TemplateRef<any>;

  constructor() {}

  setTemplate(template: TemplateRef<any>) {
    this.templateRef = template;
    this.onTemplateRefChange.emit(this.templateRef);
  }

  getTemplate() {
    return this.templateRef;
  }
}
  

<强>订阅:

export class AnotherComponent implements OnInit, OnDestroy {
  templateRef: TemplateRef<any>;
  templateSubscription: Subscription;

  constructor(private testService: TestService) {}

  ngOnInit() {
    this.templateSubscription = this.testService.onTemplateRefChange.subscribe(templateRef => {
      this.templateRef = templateRef;
    });
  }

  ngOnDestroy() {
    this.templateSubscription.unsubscribe();
  }
}