[英]Angular Dynamic Component Issue
我在其中一個組件中創建了一個動態組件,並且該組件已經制作好了,並且在html中,我將其放置在(ng-template)中:
<div type="text" class="form-control" contenteditable="true" name="phrase" (input)="triggerChange($event)">
<ng-container #container></ng-container>
</div>
triggerChange代碼:
triggerChange(event) {
let newText = event.target.innerText;
this.updateLineAndParentLineAndCreateComponent(newText);
}
這使得函數所說的內容實際上是用新文本更新了該行,並使用此更改更新了父組件,並且使運行中的組件
創建組件的代碼:
compileTemplate(line: any) {
// console.log(line[4]);
let metadata = {
selector: `runtime-component-sample`,
template: line[4]
};
let factory = this.createComponentFactorySync(this.compiler, metadata);
if (this.componentRef) {
this.componentRef.destroy();
this.componentRef = null;
}
this.componentRef = this.container.createComponent(factory);
let instance = <DynamicComponent>this.componentRef.instance;
instance.line = line;
instance.selectPhrase.subscribe(this.selectPhrase.bind(this));
}
private createComponentFactorySync(compiler: Compiler, metadata: Component, componentClass?: any): ComponentFactory<any> {
let cmpClass;
let decoratedCmp;
if (componentClass) {
cmpClass = componentClass;
decoratedCmp = Component(metadata)(cmpClass);
} else {
@Component(metadata)
class RuntimeComponent {
@Input() line: any;
@Output() selectPhrase: EventEmitter<any> = new EventEmitter<any>();
showEntities(lineIndex, entityIndex) {
this.selectPhrase.emit(entityIndex);
}
};
decoratedCmp = RuntimeComponent;
}
@NgModule({ imports: [CommonModule], declarations: [decoratedCmp] })
class RuntimeComponentModule { }
let module: ModuleWithComponentFactories<any> = compiler.compileModuleAndAllComponentsSync(RuntimeComponentModule);
return module.componentFactories.find(f => f.componentType === decoratedCmp);
}
然后根據計算出的數據在theis div中顯示一個文本,它是一個帶有html標簽的字符串,如下所示:
數據我叫foo
我觸發了內容可編輯的div的模糊事件,然后看到更改,並基於此生成具有新跨度的新字符串,並將其再次呈現為相同的div
問題是,當我從contenteditable div中刪除所有文本時,該組件已從dom中刪除,即使我嘗試再次在該字段中鍵入內容,也無法再次實例化,但它只是在div內鍵入而不是創建的組件
當用戶從字段中刪除所有文本並嘗試再次鍵入時,如何解決此問題並生成組件?
這是該項目的堆棧閃電戰: https ://stackblitz.com/edit/angular-dynamic-stack?file = src%2Fapp%2Fapp.component.ts
我發現解決方案是通過處理contenteditable div中的擊鍵,尤其是DEL和BackSpace擊鍵,因此,當輸入為空並且擊鍵是其中之一時,您只需創建一個新組件即可,但是仍然存在以下問題:動態組件不會出現動態組件它是空的或只有標簽,但這是我直到現在才想到的解決方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.