Angular: Replace placeholder with input box inside a html table at runtime

Discussão em 'Angular' iniciado por JSNinja, Dezembro 30, 2024.

  1. JSNinja

    JSNinja Guest

    I get a partial html from an API, then I need to insert input boxes by replacing a placeholder. Think of this as creating a fill in the blanks kind of a form at runtime.

    I have a solution where I split the input string into fragments using the placeholder, "~~~~~~" in this case and run a ngFor in the HTML template, set the innerHTML using the fragments and insert the input boxes.

    This works normally but breaks when a html table is provided as the input string.

    The input string from API:

    Note: This is just an example and there will be more than one input boxes in multiple rows.

    <table>
    <tr>
    <th>Name</th>
    <th>Age</th>
    </tr>
    <tr>
    <td>John</td>
    <td>~~~~~~</td>
    </tr>
    </table>


    Angular HTML template:

    <form [formGroup]="blanksForm" (ngSubmit)="onSubmit()">
    <div>
    <span *ngFor="let fragment of sentenceFragments; let i = index">
    <span [innerHtml]="fragment"></span>
    <mat-form-field *ngIf="i < sentenceFragments.length - 1" appearance="outline">
    <input matInput formControlName="blank{{ i + 1 }}" />
    </mat-form-field>
    </span>
    </div>
    <button mat-raised-button color="primary" type="submit">Submit</button>
    </form>


    TS file:

    processHtmlString() {
    const parts = this.htmlString.split('~~~~~~'); // Split by the placeholder
    for (let i = 0; i < parts.length; i++) {
    const safeFragment = this.sanitizer.bypassSecurityTrustHtml(parts);
    this.sentenceFragments.push(safeFragment);

    // Create a form control for each blank except the last one
    if (i < parts.length - 1) {
    this.blanksForm.addControl(`blank${i + 1}`, new FormControl(''));
    }
    }
    }


    Expected output:

    [​IMG]

    I think I know the problem, the table HTML structure breaks when I set the innerHTML on the span tag.

    But I can't seem to figure out a good solution to solve this problem.

    I have created a minimalistic code to demonstrate the problem.

    Stackblitz

    Any idea's are much appreciated.

    Continue reading...

Compartilhe esta Página