【问题标题】:Angular Dynamic Component Issue角度动态组件问题
【发布时间】:2018-10-14 16:55:09
【问题描述】:

我在我的一个组件中制作了一个动态组件,它已经制作好了,它在 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);
  }
  • 我根据我计算的数据在 div 中显示一个文本,它是一个带有 html 标签的字符串:

    数据我叫 foo

    • 我触发了 div 的可内容编辑的模糊事件,我看到了更改,并基于此生成了一个具有新跨度的新字符串,并再次将其渲染为相同的 div

    • 当我从 contenteditable div 中删除所有文本时,问题就出现了创建的组件

当用户从字段中删除所有文本并尝试再次输入时,我如何解决这个问题并生成组件?

这是该项目的堆栈闪电战: https://stackblitz.com/edit/angular-dynamic-stack?file=src%2Fapp%2Fapp.component.ts

【问题讨论】:

  • 参考此链接动态创建组件。 netbasal.com/…
  • 我非常了解这个链接,并且我阅读了很多它以及其他关于动态组件创建的文章,但在这种情况下没有人能帮助我
  • 而不是 createComponentFactorySync()?你可以创建一个组件类并使用'componentFactoryResolver'可注入服务来获取组件工厂吗?
  • 如果能抽出时间来创建演示应用 stackblitz,您可能会得到更快更好的答案。
  • 这里是 stackblitz 链接:stackblitz.com/edit/…

标签: javascript angular


【解决方案1】:

我发现解决方案是通过处理 contenteditable div 中的击键,尤其是 DEL 和 BackSpace Strokes,所以当输入为空并且笔划是其中之一时,您只需创建一个新组件,它仍然存在动态组件不是的问题当它为空或只有一个标签时出现,但这是我到目前为止想出的解决方法

【讨论】:

    猜你喜欢
    • 2019-02-08
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 2017-07-19
    • 2022-01-04
    • 2020-12-15
    • 2017-10-10
    • 1970-01-01
    相关资源
    最近更新 更多