2

Within a for loop in a template, I want to have some editable toggle flag to show and hide stuff which each iterated item. The item could be a row for example.

I just couldn't figure out how to create a local variable easily. I don't want to create a component for each row or some directive. Because in Angular1, you can just ng-init="editable=false", and somewhere within the child dom, you can just toggle is by editable=!editable and this is in the scope of this particular child which all makes sense.

Please help me improve this, currently this will toggle all the rows. I need to have local variable for each row.

<div *ngFor="let c of comments">
  <button (click)="editable=!editable">edit</button>
  <p *ngIf="editable"><textarea>{{c.message}}</textarea></p>
</div>

How to do this in angular2~4?

1
  • 1
    Why not just make "editable" a property of each "comment"? Even if the data needs to go elsewhere it's pretty trivial to strip out or add in the property as required. Commented May 12, 2017 at 9:30

1 Answer 1

4
<div *ngFor="let c of comments;let i=index">
  <button (click)="toggleEditable(i)">edit</button>
  <p *ngIf="editable[i]"><textarea>{{c.message}}</textarea></p>
</div>
editable = [true, false, true];

toggleEditable(idx) {
  this.editable[idx] = !this.editable[idx];
} 

editable needs to have the same number of values as comments.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.