是否可以保存对动态组件的引用,并在以后@ Input / @ Output更新它?

时间:2018-07-30 12:56:48

标签: javascript angular contenteditable angular6 angular-dynamic-components

我正在与contenteditable div合作。而且我想在用户按下“ Shift + 2”时将其插入其中。在按下键盘时,我正在创建像这样的动态组件:

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中的组件未更新。以后可以动态更新吗?我可以在创建过程中在addComponent中设置@Input属性,但是以后如何更新?

0 个答案:

没有答案