我认为你可以提供用户使用组件作为插件。该组件必须扩展您的抽象基础插件组件。
例如clear-styles 插件可能看起来像
@Component({
selector: `nw-clear-styles-button`,
template: `
<button (click)="clearStyles($event)"
[disabled]="editMode || disabled"
class="nw-button clear-styles" title="Clear Styles">
Clear Styles
</button>`
})
export class NwClearStylesButtonComponent extends Ng2WigPluginComponent {
constructor() {
super();
}
clearStyles() {
const div = document.createElement('div');
div.innerHTML = this.content;
this.contentChange.emit(div.textContent);
}
}
format插件
@Component({
selector: `nw-formats-button`,
template: `
<select class="nw-select"
[(ngModel)]="format"
(ngModelChange)="execCommand('formatblock', format.value)"
[disabled]="editMode || disabled">
<option *ngFor="let format of formats" [ngValue]="format">{{ format.name }}</option>
</select>
`
})
export class NwFormatButtonComponent extends Ng2WigPluginComponent {
formats = [
{name: 'Normal text', value: '<p>'},
{name: 'Header 1', value: '<h1>'},
{name: 'Header 2', value: '<h2>'},
{name: 'Header 3', value: '<h3>'}
];
format = this.formats[0];
constructor() {
super();
}
}
Ng2WigPluginComponent 是您的库提供的抽象基类:
export abstract class Ng2WigPluginComponent {
execCommand: Function;
editMode: boolean;
content: string;
editModelChange: EventEmitter<boolean> = new EventEmitter();
contentChange: EventEmitter<string> = new EventEmitter();
}
因此用户可以轻松地使用在基类中声明的属性。
要注册此类插件,我们可以使用您提到的forRoot 方法。为此,您需要
1)如下配置你的库模块:
ng2wig.module.ts
@NgModule({
...
})
export class Ng2WigModule {
static forRoot(entryComponents: CustomButton[]) {
return {
ngModule: Ng2WigModule,
providers: [
Ng2WigToolbarService,
{provide: NG_WIG_CUSTOM_BUTTONS, useValue: entryComponents},
{provide: ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: entryComponents},
]
};
}
}
在哪里
-
NG_WIG_CUSTOM_BUTTONS 是您的全局库令牌,用于识别库中提供的插件
ng2wig-toolbar.service.ts
@Injectable()
export class Ng2WigToolbarService {
constructor(@Optional() @Inject(NG_WIG_CUSTOM_BUTTONS) customButtons: CustomButton[]) {
if (customButtons) {
customButtons.forEach(plugin => this.addCustomButton(plugin.pluginName, plugin.component));
}
}
-
ANALYZE_FOR_ENTRY_COMPONENTS 是 Angular 全局令牌,能够动态加载插件
2) 在 AppModule 模块的声明数组中声明 NwClearStylesButtonComponent
3) 将其传递给Ng2WigModule.forRoot 方法
Ng2WigModule.forRoot([
{ pluginName: 'clear-styles', component: NwClearStylesButtonComponent },
{ pluginName: 'format', component: NwFormatButtonComponent }
])
然后您的主要任务是使用ComponentFactoryResolver 和ViewContainerRef 动态生成组件(请参阅下面的plunker 中的ng2wig-plugin.directive.ts)
Plunker Example