繁体   English   中英

角动态组件问题

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM