1

我正在使用 contenteditable div。当用户按下“shift+2”时,我想插入它的组件。在 keydown 我正在创建这样的动态组件:

addComponent(uuid: string) {
    const component = BodyVariableComponent;
    // Here is i want to save component ref into variable:
    this.variableComponentRef = this.componentFactoryResolver
      .resolveComponentFactory(component)
      .create(this.injector);
    this.variableComponentRef.instance.uuid = uuid;
    this.variableComponentRef.changeDetectorRef.detectChanges();
    this.appRef.attachView(this.variableComponentRef.hostView);
    const domElem = <HTMLElement>(<EmbeddedViewRef<BodyVariableComponent>>this.variableComponentRef.hostView).rootNodes[0];
    // This function insert dom into carret position
    this.pasteDomElementAtCaret(domElem);
  }

这是将dom元素插入carret位置的功能。

 pasteDomElementAtCaret(domElement: HTMLElement) {
    let selection, range;
    if (window.getSelection) {
      selection = window.getSelection();
      if (selection.getRangeAt && selection.rangeCount) {
        range = selection.getRangeAt(0);
        range.deleteContents();
        const el = document.createElement('div');
        el.innerHTML = domElement.outerHTML;
        const frag = document.createDocumentFragment();
        let node, lastNode;
        while ( (node = el.firstChild) ) {
            lastNode = frag.appendChild(node);
        }
        range.insertNode(frag);
        // Preserve the selection
        if (lastNode) {
            range = range.cloneRange();
            range.setStartAfter(lastNode);
            range.collapse(true);
            selection.removeAllRanges();
            selection.addRange(range);
        }
      }
    }
  }

然后我想通过保存的引用来更新这个组件:

updateComponentTitle(value: string) {
    this.variableComponentRef.instance.value = value;
    this.variableComponentRef.changeDetectorRef.detectChanges();
  }

但这不起作用。dom 中的组件没有更新。以后可以动态更新吗?我可以在创建过程中设置@Input 属性addComponent,但是以后如何更新呢?

4

0 回答 0