Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 - get ViewRef of current component

Tags:

angular

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?

like image 547
user3384985 Avatar asked Oct 17 '22 05:10

user3384985


1 Answers

Inject the ChangeDetectorRef.

export class ExampleComponent {
   constructor(@Inject(ChangeDetectorRef) view: ViewRef) {
   }
}
like image 77
Paul Draper Avatar answered Oct 21 '22 02:10

Paul Draper