8

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?

6
  • 2
    The best way is to get it after creation some component dynamically Commented Sep 23, 2017 at 16:06
  • 1
    What do you want to do with ViewRef? Seems you want to remove the component from inside it. I don't think it's a good idea to try to remove a component imperatively that was added by Angular. Commented Sep 23, 2017 at 16:07
  • 1
    Provide the ViewRef in the constructor of the component. Commented Sep 23, 2017 at 16:07
  • 3
    @GünterZöchbauer stackoverflow.com/questions/46376328/… Commented Sep 23, 2017 at 16:07
  • 1
    Please provide minimal working example of how you are creating your components Commented Sep 23, 2017 at 16:10

2 Answers 2

5

Inject the ChangeDetectorRef.

export class ExampleComponent {
   constructor(@Inject(ChangeDetectorRef) view: ViewRef) {
   }
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.