0

My problem will for sure seems very simple for some people but I struggle finding a simple solution to achieve this:

  • In a ngFor loop, I display some items ID and date. On each item i want to add a delete button.

  • This button is disabled by default and only activated if I tick a checkbox (as a confirmation for deletion).

Here is my code:

<tr *ngFor="let item of itemsArray ">
    <td>{{item .date | date:'short'}}</td>
    <td>{{item .id}}</td>
    <td>Delete?
      Yes, Sure: <input type="checkbox">
      <br>
      <button [disabled]="" (click)="delete(item .id")></button>
    </td>
<tr>

On app.component.ts, there is only one variable to go through:

const itemsArray = [
    {id: 1, date: 1488170777813},
    {id: 2, date: 1488170777813},
    {id: 5, date: 1488170777813},
    {id: 3, date: 1488170777813},
    {id: 4, date: 1488170777813}
];

Delete function is just a http.delete() to remote API.

My question is: how ton bind the checkbox with disable state of my button since i'm inside a loop?

2
  • Post your whole code, with itemsArray variable, etc. Commented Mar 2, 2017 at 0:12
  • I just added some more information. Thanks :) Commented Mar 2, 2017 at 1:19

1 Answer 1

2

You can add one more field in itemsArray as

const itemsArray = [
    {id: 1, date: 1488170777813, disabled: true},
    {id: 2, date: 1488170777813, disabled: true},
    {id: 5, date: 1488170777813, disabled: true},
    {id: 3, date: 1488170777813, disabled: true},
    {id: 4, date: 1488170777813, disabled: true}
];

And then in your template u can use as

<tr *ngFor="let item of itemsArray">
    <td>{{item.date | date:'short'}}</td>
    <td>{{item.id}}</td>
    <td>Delete?
      Yes, Sure: <input type="checkbox" [(ngModel)]="item.disabled" checked="!item.disabled">
      <br>
      <button [disabled]="item.disabled" (click)="delete(item.id")></button>
    </td>
</tr>
Sign up to request clarification or add additional context in comments.

3 Comments

It's a nice idea but it lead to change my data model after having got it from http request.
yes but I didn't find any other way to do that.because we need to track which checkbox is clicked.
Since we sre inside a ngfor do you think we could be able to use index to buils reference on the go? I dont know how we can add index to create for example an attribute such #checkbox{$index} and then check the value inside the [disabled]?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.