Angular 4 - 获取当前组件的ViewRef

时间:2017-09-23 16:04:44

标签: angular

如何获得当前ViewRef的{​​{1}} -

我想从服务中获取component。这是代码 -

component.service.ts

ViewRef

component.ts

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

@Injectable()
export class CheckboxService{

constructor(private viewRef: ViewRef){
}

getViewRef(){
    return this.viewRef;
}
}

我收到以下错误 -

  

没有ViewRef的提供者!

获取当前组件import { Component, EventEmitter, Output, ViewChild, ViewRef } from '@angular/core'; import { AddFormDirective } from '../../add-form/add-form.directives'; import { CheckboxService } from './checkbox.service'; @Component({ selector: 'ang-checkbox', templateUrl: './checkbox.component.html' }) export class CheckboxViewComponent { @ViewChild(AddFormDirective) addFormDirective: AddFormDirective; constructor(private checkboxService: CheckboxService){ } remove_element(){ let viewContainerRef = this.addFormDirective.viewContainerRef; let currentComponentIndex = viewContainerRef.indexOf(this.checkboxService.getViewRef()); viewContainerRef.remove(currentComponentIndex); } } 的最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

  1. 使用ComponentFactoryResolver将组件解析为componentFactory;
  2. 从ViewContainerRef方法获取ComponentRef,该方法调用createComponent;
  3. 访问ComponentRef ['hostView']。

答案 1 :(得分:0)

注入ChangeDetectorRef

export class ExampleComponent {
   constructor(@Inject(ChangeDetectorRef) view: ViewRef) {
   }
}