spfxsharepointframework

SharepointFramework - how to set the actual webpart code as initial value in PropertyFieldCodeEditor


Hello i am using this custom property pane control called PropertyFieldCodeEditor. what i want is to display the actual webpart code as the initial value of the code editor, then after i click save, the changes will be reflected on the webpart..

this is the code of PropertyFieldCodeEditor

PropertyFieldCodeEditor('htmlCode', {
    label: 'Edit Code',
    panelTitle: 'Edit Code',
    initialValue: "",
    onPropertyChange: this.onPropertyPaneFieldChanged,
    properties: this.properties,
    disabled: false,
    key: 'codeEditorFieldId',
    language: PropertyFieldCodeEditorLanguages.HTML
  })

i tried to put this.domElement on initialvalue but it only accept string, also i cand find a way to convert this.domelement to string..

also what should i put inside

protected onPropertyPaneFieldChanged(path: string, newValue: string) {}

Solution

  • For initialValue, you should be able to use this.domElement.innerHTML or this.domElement.outerHTML. Both are strings representing the contents of domElement (note, domElement is really just an HTMLElement).

    <div style="width: 100%;">
      <div class="helloWorld_d3285de8">
        ...
      </div>
    </div>
    
    <div class="helloWorld_d3285de8">
      ...
    </div>
    

    You'll probably want innerHTML, since that's what's initially used in the render method.

    Once you set the initialValue, you would have accomplished copying your web part code into the PropertyFieldCodeEditor. Now you would need to get the PropertyFieldCodeEditor contents (which is stored in your property htmlCode) assigned back into this.domElement.innerHTML.

    Unfortunately, in onPropertyPaneFieldChanged, this points to the PropertyFieldCodeEditor, not to the web part class anymore. You may or may not be able to do it here - I didn't look too deeply into it.

    The easiest solution I figured was, in render, to assign this.domElement.innerHTML like so:

    public render(): void {
      this.domElement.innerHTML = this.properties.htmlCode || `
        <div class="${styles.helloWorld}">
          ...
        </div>`;
    }
    

    This way, the web part will initially render whatever comes after the ||. But as soon as you save a change to the PropertyFieldCodeEditor, it will start rendering the htmlCode instead. This only works because initially htmlCode is undefined. (Note it won't work exactly like this if you assign something truthy to it via your web part's preconfiguredEntries - you would have to write some further checks. The principle is the same, though.)