检查Angular2中的复选框时启动事件

sel*_* mn 39 data-binding checkbox html5 typescript angular

我是Angular2的新手,在全局的web中,我想在检查checkbox和/或取消选中时使用Material-Design,在数据库中启动一个更改oject参数值的操作,我试过[(ngModel)]但没有发生任何事情.这个想法是,我必须添加一些命题与checked | unchecked状态,判断它是一个truefalse命题.这是命题模型

    export class PropositionModel {
        id:string;
        wordingP:string; // the proposition
        propStatus:Boolean; // the proposition status
}
Run Code Online (Sandbox Code Playgroud)

这是一个命题的Html代码:

<div class="uk-width-xlarge-1-1 uk-width-medium-1-2">
                <div (submit)="addProp1()" class="uk-input-group">
                    <span class="uk-input-group-addon"><input type="checkbox"  data-md-icheck/></span>
                    <label>Proposition 1</label>
                    <input [(ngModel)]="proposition1.wordingP" type="text" class="md-input" required class="md-input"/>
                </div>
            </div>
Run Code Online (Sandbox Code Playgroud)

这是用于添加命题的TypeScript代码:

addProp1() {
        this.proposition1 = new PropositionModel();
        this.proposition1.propStatus = false;
        this.propositionService.addProposition(this.proposition1)
            .subscribe(response=> {
                console.log(response);
                console.log(this.proposition1);
                this.proposition1 = new PropositionModel();})
    }
Run Code Online (Sandbox Code Playgroud)

并且你可以看到我false默认为它做了一个proposition status,我想在检查命题后改变它.这是一个图像如何寻找更好的问题理解. 在此输入图像描述

有什么帮助吗?

Ank*_*ngh 89

PLUNKER DEMO

模板: 使用change事件来调用函数并传递事件.

<input type="checkbox"  data-md-icheck (change)="addprop1($event)"/>
Run Code Online (Sandbox Code Playgroud)

TS: 在添加属性之前接收事件并检查是否选中了复选框.

addProp1(e) {

   if(e.target.checked){
        this.proposition1 = new PropositionModel();
        this.proposition1.propStatus = false;
        this.propositionService.addProposition(this.proposition1)
            .subscribe(response=> {
                console.log(response);
                console.log(this.proposition1);
                this.proposition1 = new PropositionModel();})
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,它是(更改)而不是(onChange)。我的愚蠢错误花了我几分钟的时间才弄清楚 (2认同)

Jak*_*ner 12

如果向ngModel引用添加双重paranthesis,则会获得与model属性的双向绑定.然后可以在事件处理程序中读取和使用该属性.在我看来,这是最干净的方法.

<input type="checkbox" [(ngModel)]="myModel.property" (ngModelChange)="processChange()" />
Run Code Online (Sandbox Code Playgroud)


Gün*_*uer 6

你可以使用ngModel喜欢

<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>
Run Code Online (Sandbox Code Playgroud)

通过更新checkboxValue代码中的属性以及用户更改复选框时更新复选框状态addProp().