gpt4 book ai didi

Angular 4 - 获取当前组件的ViewRef

转载 作者:行者123 更新时间:2023-12-02 10:41:41 25 4
gpt4 key购买 nike

我如何获取当前组件ViewRef -

我正在尝试从服务获取ViewRef。这是代码 -

component.service.ts

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

@Injectable()
export class CheckboxService{

constructor(private viewRef: ViewRef){
}

getViewRef(){
return this.viewRef;
}
}

组件.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);
}
}

我收到以下错误 -

No provider for ViewRef!

获取当前组件的ViewRef的最佳方式是什么?

最佳答案

注入(inject)ChangeDetectorRef

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

关于Angular 4 - 获取当前组件的ViewRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46381569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com