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?
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.ViewRefin the constructor of the component.