我正在开发一个项目,我们正在创建一种带有可编辑组件小部件的CMS。对于可编辑的每个组件,服务中的标志使编辑按钮显示在可编辑组件旁边。
我创建了一个可以添加到元素选择器的属性指令,使用ViewContainerRef和ComponentFactoryResolver创建编辑按钮组件的实例并将其注入。我遇到的问题是,理想情况下,我希望将注入的组件放在选择器内,并在其上调用属性指令。目前,它会在调用attributre指令的元素之后放置动态注入的组件。
修改-button.directive.ts
import { Directive, ComponentFactoryResolver, ViewContainerRef, ElementRef } from '@angular/core';
import { EditButtonComponent } from './edit-button.component';
import { Config } from '../../portal-widgets/services/config.service';
@Directive({ selector: '[pctEditable]' })
export class EditableDirective {
constructor(private resolver: ComponentFactoryResolver, private location:
ViewContainerRef, public config: Config, private element: ElementRef ) {
}
ngOnInit() {
var editMode = this.config.get('edit-mode');//Set variable based on edit-mode
if( editMode == true ){ //check if edit mode = true in config service
var loc = <any>(this.location);
var myParentComponent = loc._data.componentView.component;
const factory = this.resolver.resolveComponentFactory(EditButtonComponent);// create component
factory of edit component
let ref = this.location.createComponent(factory);// insert created component instance into element
ref.instance.widget = myParentComponent;
}
}
}
修改-button.component
<!-- button to activate form dialogue box and pop-up directive with parameters-->
<button type="text" (click)="showDialog()" pButton label="Show" class="button-edit-widget"><i class="fa fa-pencil" aria-hidden="true"></i>
</button>
<p-dialog header="Edit Form" [(visible)]="display" modal="modal" responsive="true" [draggable]=false >
<!-- directive for form-->
<portal-dynamic-form [widget]="widget"></portal-dynamic-form>
</p-dialog>
可编辑的组件选择器中的用法
<portal-text-widget #widget widgetId="text-hb" pctEditable></portal-text-widget>
我的注射格式如下
<portal-text-widget pcteditable="" widgetid="text-hb" ng-reflect-widget-id="text-hb">...</portal-text-widget>
<portal-edit-button ng-version="4.0.1">...</portal-edit-button>
但我真的更喜欢这个
<portal-text-widget pcteditable="" widgetid="text-hb" ng-reflect-widget-id="text-hb">...<portal-edit-button ng-version="4.0.1">...</portal-edit-button>
</portal-text-widget>