Search code examples
javascriptangularangular-formly

Bind to template of formly field on click of other field in angular formly


I have been using a formly form that has a section in which I display dynamic HTML, I made use of the template field in which I am initializing HTML on load. When I click the other field value I need to change this HTML however the value change is assigned but not reflected in HTML UI, I have created stackblitz example for the scenario:

Stackblitz Click here

Please find below code snippet :

Initialized HTML value is following:

htmlValue = '<p>test</p>';

Field value assigned:

{ template : this.htmlValue }

On click of submit button assigned HTML should be expected output:

this.htmlValue = `

          <p class="mb-2"><b>Maximum  Spend Per Cricketer:</b></p>
          <div class="alert alert-secondary border flex-column mb-0">
            <div class="row">
              <div class="col">Snacks:</div>
              <div class="col">$15.00</div>
            </div>
            <div class="row">
              <div class="col">Breakfast:</div>
              <div class="col">$25.00</div>
            </div>
            <div class="row">
              <div class="col">Lunch:</div>
              <div class="col">$45.00</div>
            </div>
          </div>
        </div>`;

How can I achieve this output?


Solution

  • I will use a simple code to explain your problem

    let a = 4;
    let b = {a}
    a= 8;
    
    console.log({a})
    console.log({b})

    Its a simple explanatory, you changed a but b didn't change. Same to your case, you have changed htmlValue but fields is not changed. A simple way to solve this would be to use a getter

      get fields(): FormlyFieldConfig[] {
        return [
          {
            key: "header",
            type: "input",
            templateOptions: {
              type: "text",
              label: "Page Header",
              placeholder: "Enter page header",
              required: true
            }
          },
          {
            template: this.htmlValue
          }
        ];
      }
    
    

    With a getter, whenever the value of htmlValue changes, the value of fields would change

    Edit

    Another option would be to simply change the value of the template section in four formly object

    this.fields[1].template = this.htmlValue;
    

    See Demo Here