Home > Back-end >  HTML input with content related to an ngFor
HTML input with content related to an ngFor

Time:08-09

This is my template code extract:

<ul >
  <li *ngFor="let paragraph of selectedExperience.description">
    <div *ngIf="!editMode">
      {{ paragraph }}
    </div>
    <input
      *ngIf="editMode"
      {{paragraph}}
      id="paragraph"
      type="text"
      name="paragraph"
      placeholder="Párrafo"
    />
    <button
      (click)="deleteParagraph(selectedExperience, paragraph)"
      *ngIf="editMode"
      
    >
      <svg>
        ...
      </svg>
    </button>
  </li>
</ul>

My intention is to have each of the paragraphs shown as an input when editMode is enabled but I don't know how to do it. I know something must be wrong with the input. Also I didn't use [(ngModel)] because it didn't let me unless I did something like:

[(ngModel)]="selectedExperience.description![0]"

This is how it looks when editMode = false enter image description here

And this is (the problem) how it looks when editMode = true enter image description here

CodePudding user response:

Update:

Asnwer derived from here do upvote that answer! Do not update the variable, but update the array property using the index!

<hello name="{{ name }}"></hello>
<p>Start editing to see some magic happen :)</p>
<input type="text" [value]="name" />
<li *ngFor="let paragraph of test; let i = index; trackBy: trackBy">
  <input type="text" [(ngModel)]="test[i]" />
</li>
{{ test | json }}

angular code

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular';
  test = ['123', '456'];
  trackBy(index, item) {
    return index;
  }
}

stackblitz

how about this? use the ngModel binding and set the paragraph to it.

<ul >
  <li *ngFor="let paragraph of selectedExperience.description">
    <div *ngIf="!editMode">
      {{ paragraph }}
    </div>
    <input
      *ngIf="editMode"
      id="paragraph"
      [(ngModel)]="paragraph"
      type="text"
      name="paragraph"
      placeholder="Párrafo"
    />
    <button
      (click)="deleteParagraph(selectedExperience, paragraph)"
      *ngIf="editMode"
      
    >
      <svg>
        ...
      </svg>
    </button>
  </li>
</ul>
  • Related