0

I want to have a checkbox attached to each text of my list.
Like this:

  1. Text1 [Checkbox1]
  2. Text2 [Checkbox2]
  3. Text3 [Checkbox3]
  4. Text4 [Checkbox4]

The list is dynamic therefore checkboxes should also appear dynamically next to each item of the list.

I should be able to set the default value of each checkbox in the beginning and also gather their values when user clicks on them.

I have tried this:

<div *ngIf = "blogs.length > 0">

    <ul>
    <li *ngFor = "let blog of blogs" 
        (click)          = "onSelect(blog)" 
        [class.selected] = "blog === clickedOnThisBlog">

        <a *ngIf = "blog.show === true" routerLink = "/editor/{{blog.id}}">
            {{blog.title}} 
            creationDate: {{blog.creationDate}}
            modificationDate: {{blog.modificationDate}}
        </a>

        <a *ngIf = "blog.show === true">
            <input type     = "checkbox" 
            [ngModel]       = "checkboxChecked"
            #checkbox_l     = "ngModel"
            value           = "blog"
            (click)         = "onCheckboxClicked( checkbox_l, value )"  >
        </a>
    </li>
    </ul>
</div>

The first half of this code shows the list of text. In second half I have attempted to attach the checkboxes with each of the text.

I don't know how to link the list of checkboxes back to the .ts file so that I can control them at one place there.

This is a template driven code. ngModel has to be used.

What's the way out?

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411
  • You need a specific model for every checkbox. Maybe using the index value of your for loop and have a ngModel array? – Terry Apr 11 '20 at 07:14

1 Answers1

0

I defined an array in the corresponding .ts file as follows:
checkboxes: CheckboxStructure[] = []

CheckboxStructure is defined as follows:

export interface CheckboxStructure
{
  id:     number
  value:  boolean
}

I wrote let i = index in *ngFor and attached my checkboxes array's particular field to [ngModel] like this: [ngModel] = "checkboxes[i].value"

<div *ngIf = "blogs.length > 0">

    <ul>
    <li *ngFor = "let blog of blogs; let i = index;" >

        <a *ngIf = "blog.show === true" routerLink = "/editor/{{blog.id}}">
            {{blog.title}}
            creationDate: {{blog.creationDate}}
            modificationDate: {{blog.modificationDate}}
        </a>

        <a *ngIf = "blog.show === true">
            <input type = "checkbox" 
            [ngModel]   = "checkboxes[i].value">
        </a>
    </li>
    </ul>

</div>

Credit: *ngFor how to bind each item in array to ngModel using index

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411