如何获得当前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);
}
}
的最佳方法是什么?
答案 0 :(得分:0)
答案 1 :(得分:0)
注入ChangeDetectorRef
。
export class ExampleComponent {
constructor(@Inject(ChangeDetectorRef) view: ViewRef) {
}
}