Атрибуты теряются при установке значения вершины - PullRequest
0 голосов
/ 20 марта 2019

У меня есть несколько вершин, которые мне нужно обновить программно в соответствии с данными, которые регулярно обновляются с сервера.Сначала создается вершина следующим образом:

  const doc = (<any>window).mxUtils.createXmlDocument();
      var node = doc.createElement('kw');
      node.setAttribute(AppSettings.SINGLE_LINE_DIAGRAM_ATTRIBUTES.KEY, treeItem.tag.key.value);
      node.setAttribute(AppSettings.SINGLE_LINE_DIAGRAM_ATTRIBUTES.TYPE, treeItem.tag.key.type);
      node.setAttribute(AppSettings.SINGLE_LINE_DIAGRAM_ATTRIBUTES.MEASUREMENT_TYPE, measurementType);
      node.setAttribute(AppSettings.SINGLE_LINE_DIAGRAM_ATTRIBUTES.FIELD_NAME, fieldType);
      node.setAttribute(AppSettings.SINGLE_LINE_DIAGRAM_ATTRIBUTES.CELL_TYPE, 'label');

    try {
      const parent = this.graph.getDefaultParent();
      this.graph.getModel().beginUpdate();
      const vertex = this.graph.insertVertex(parent, uuid.v4(), node, 50, 50, 80, 40,"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;editable=0;",''); 
    } finally {
      this.graph.getModel().endUpdate();
    }

Затем мне нужно обновить значение с помощью данных с сервера, я делаю это так: я получаю ячейку из словаря и обновляю ее:

const value = this.getCellValue(item);
this.graph.model.setValue(cell, value);

Увы!клетка теряет все свои атрибуты.Которые необходимы, чтобы сделать новый запрос к серверу (например, ключ).

Буду признателен за любую помощь.

1 Ответ

0 голосов
/ 25 марта 2019

Я нашел решение. Я использовал эту ссылку .
Я начал свой проект, используя этот проект .

Я создал класс, который наследует от mxgraph, переопределяющего convertValueToString и cellLabelChanged.

export class myMxGraph extends mxGraph
{
    convertValueToString(cell:mxCell)
    {
        if ((<any>window).mxUtils.isNode(cell.value))
        {
            return cell.getAttribute('label', '')
        }
    }


cellLabelChanged(cell, newValue, autoSize)
{
  if ((<any>window).mxUtils.isNode(cell.value))
  {
    // Clones the value for correct undo/redo
    var elt = cell.value.cloneNode(true);
    elt.setAttribute('label', newValue);
    newValue = elt;
  }

  super.cellLabelChanged(cell, newValue,autoSize);
};


}

Как это использовать:

import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';
import beautify from 'xml-beautifier';
import { myMxGraph } from './myMxGraph';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements AfterViewInit {

      @ViewChild('graphContainer') graphContainer: ElementRef;
      vertexCreated = false;
      graph: myMxGraph;
      vertex:mxCell;
      jsonText = "";
      ngAfterViewInit() {
        this.graph = new myMxGraph(this.graphContainer.nativeElement);
      }


    createNewVertex(): void {

      const itemStyle = "";
      const doc = (<any>window).mxUtils.createXmlDocument();
      var node = doc.createElement('vertex');
      node.setAttribute('type', 'aaaa');

      try {
        const parent = this.graph.getDefaultParent();
        this.graph.getModel().beginUpdate();
        this.vertex = this.graph.insertVertex(parent, "uuid.v4()", node, 50, 50, 30, 80,itemStyle,'');
        this.vertex.setAttribute('label', 'Vertex');
      } finally {
        this.graph.getModel().endUpdate();
      }
      this.vertexCreated = true;
    }


    updateInput()
    {
      var encoder = new (<any>window).mxCodec();
      var node = encoder.encode(this.graph.getModel());
      this.jsonText =   beautify((<any>window).mxUtils.getXml(node));
    }


    updateVertex()
    {
      try {
        this.graph.getModel().beginUpdate();
        this.vertex.value.setAttribute('label','yael');
        const color = '#ff69b4';
                const style = this.vertex.getStyle();
                var styleArr = style.split(';')

                var styleArr = style.split(';');
                var res = styleArr.filter(function (value) { 
                    return !value.includes('strokeColor'); 
                  });
                  res.unshift( 'strokeColor='+ color);
                  this.vertex.setStyle(res.join(';'));
        this.graph.refresh(this.vertex);
        }
        finally
        {
          this.graph.getModel().endUpdate();
        }
    }

    }

Таким образом, mxcell является частью клонированного узла xml даже после изменения метки, поэтому атрибуты не теряются.

...