在Angular 7模态服务中,我正在创建模态Stackblitz。
模态只是添加到文档中的DIV,如下所示:
const modal = document.createElement('div');
modal.classList.add('modal');
modal.appendChild(this.element);
document.body.appendChild(this.modal);
modal
内容(this.element)是动态创建的组件。
我希望modal
也是动态添加的组件:
有人可以帮我解决(3)和(4)吗?不知道该怎么做。
模式
export class Modal {
protected modal: any = null;
close() {
this.modal.close();
}
}
ModalService
import { ApplicationRef, ComponentFactoryResolver, EmbeddedViewRef, Injectable, Injector, ComponentRef, ReflectiveInjector } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ModalService {
private component: ComponentRef<any>;
private element: any;
private stage: any;
constructor(private componentFactoryResolver: ComponentFactoryResolver, private application: ApplicationRef, private injector: Injector) { }
open(component: any, data: any): void {
if(this.element)
return;
const injector: Injector = ReflectiveInjector.resolveAndCreate([{ provide: 'modal', useValue: data }]);
this.component = this.componentFactoryResolver.resolveComponentFactory(component).create(injector);
this.component.instance.modal = this;
this.application.attachView(this.component.hostView);
this.element = (this.component.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
const modal = document.createElement('div');
modal.classList.add('modal');
modal.appendChild(this.element);
document.body.appendChild(this.modal);
}
close(): void {
this.application.detachView(this.component.hostView);
this.stage.parentNode.removeChild(this.stage);
this.component.destroy();
this.element = null;
}
}
答案 0 :(得分:2)
首先,您需要动态创建该内部组件,然后在extension UIFont {
public static func CreateWithStyle(name: String, size: CGFloat, styles: [UIFontDescriptor.SymbolicTraits]) -> UIFont {
let fontDescriptor = UIFontDescriptor(name: name, size: size)
var fontAtrAry = fontDescriptor.symbolicTraits
if styles.count > 0 {
for style in styles {
fontAtrAry.update(with: style)
}
}
return UIFont(descriptor: fontDescriptor.withSymbolicTraits(fontAtrAry)!, size: size)
}
}
方法中使用projectableNodes
参数将其投影到动态创建的ComponentFactory.create
中。
该ModalComponent应该在其模板中具有ng-content标签:
ModalComponent
modal.service.ts
<div class="stage">
<div class="modal">
<ng-content></ng-content>
</div>
</div>