Angular 4 checkbox change value

2019-04-04 10:26发布

how could you achieve in Angular 4 that when you register in a checkbox save an "A" or "B" value. As much as I try, he is only sending me true or false, I hope someone can help me.

registry.component.ts

  this.userForm = new FormGroup({
   state: new FormControl('',),

  });

registry.component.html

<div class="form-group">
                <label>State</label>
          <input type="checkbox" [(ngModel)]="isChecked" (change)="checkValue(isChecked?'A':'B')" formControlName="state"/>
        </div>  

            <pre>{{userForm.value | json}}</pre>

That way I can get the console to show the value I want (A or B) but in the JSON is still true or false.

7条回答
时光不老,我们不散
2楼-- · 2019-04-04 10:34

This it what you are looking for:

<input type="checkbox" [(ngModel)]="isChecked" (change)="checkValue(isChecked?'A':'B')" />

Inside your class:

checkValue(event: any){
   console.log(event);
}

Also include FormsModule in app.module.ts to make ngModel work !

Hope it Helps!

查看更多
该账号已被封号
3楼-- · 2019-04-04 10:37

Another approach is to use ngModelChange:

Template:

<input type="checkbox" ngModel (ngModelChange)="onChecked(obj, $event)" />

Controller:

onChecked(obj: any, isChecked: boolean){
  console.log(obj, isChecked); // {}, true || false
}

I prefer this method because here you get the relevant object and true/false values of a checkbox.

查看更多
小情绪 Triste *
4楼-- · 2019-04-04 10:39

I am guessing that this is what something you are trying to achieve.

<input type="checkbox" value="a" (click)="click($event)">A
<input type="checkbox" value="b" (click)="click($event)">B

click(ev){
   console.log(ev.target.defaultValue);
}
查看更多
在下西门庆
5楼-- · 2019-04-04 10:42

Give a try on this,

Template

<input (change)="FieldsChange($event)" value="angular" type="checkbox"/>

Ts File

FieldsChange(values:any){
console.log(values.currentTarget.checked);
}
查看更多
干净又极端
6楼-- · 2019-04-04 10:46
changed = (evt) => {    
this.isChecked = evt.target.checked;
}

<input type="checkbox" [checked]="checkbox" (change)="changed($event)" id="no"/>
查看更多
甜甜的少女心
7楼-- · 2019-04-04 10:47

You can use this:

<input type="checkbox" [checked]="record.status" (change)="changeStatus(record.id,$event)">

And on your ts file,

changeStatus(id, e) {
    var status = e.target.checked;
    this.yourseverice.changeStatus(id, status).subscribe(result => {
        if (status)
            this.notify.success(this.l('AddedAsKeyPeople'));
        else
            this.notify.success(this.l('RemovedFromKeyPeople'));

    });
}

Here, record is the model for current row and status is boolean value.

查看更多
登录 后发表回答