Angular5 get Value of Input on Click

时间:2018-01-23 19:21:22

标签: angular

I have a Form, and I want, if the Checkbox is checked, that the value is submitted with the isChecked function. But i can't get it working. I tried it with isChecked({{user.username}}) But this is not working. Any Idea?

<form #a="ngForm" (ngSubmit)="addGamers(a)">
      <ul class="list-group gamer-list">
            <li class="list-group-item agamer" *ngFor="let user of allUsers$ | async as users; index as i">
                <div class="material-switch">
                    <input id="switch{{user.username}}" value="switch{{user.username}}" name="switchUsername" (click)="isChecked()" type="checkbox"/>
                    <label for="switch{{user.username}}" class="switch{{user.key}}"></label>
                </div>
                {{user.username}} {{ i }}
            </li>
    </ul>

1 个答案:

答案 0 :(得分:0)

When you provide the attrs within (), you can access the angular variables directly like

<input id="switch{{user.username}}" value="switch{{user.username}}" name="switchUsername" (click)="isChecked(user.username)" type="checkbox"/>

and in your component, you can access the function directly:

isChecked(userName) { 
   if (userName != null) {
      // your implementation
   }
}

if you want to make it onSubmit, then you can use the power of two-way binding in angular2+

in your component:

public isChecked: boolean = false;

in Html:

<input id="switch{{user.username}}" value="switch{{user.username}}" name="switchUsername" [(ngModel)]="isChecked" type="checkbox"/>