user3384985
user3384985

Reputation: 3017

Angular 4 - get ViewRef of current component

How can i get the ViewRef of my current component -

I am trying to get ViewRef from a service. Here is the code -

component.service.ts

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

@Injectable()
export class CheckboxService{

constructor(private viewRef: ViewRef){
}

getViewRef(){
    return this.viewRef;
}
}

component.ts

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);
}
}

I get following error -

No provider for ViewRef!

What is the best way to get ViewRef of current component?

Upvotes: 8

Views: 11488

Answers (2)

Paul Draper
Paul Draper

Reputation: 83393

Inject the ChangeDetectorRef.

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

Upvotes: 5

H.jame
H.jame

Reputation: 75

  1. resolve Component to componentFactory with ComponentFactoryResolver;
  2. get ComponentRef from the method of ViewContainerRef which call createComponent;
  3. access ComponentRef['hostView'].

Upvotes: 0

Related Questions