2016-05-06 41 views
20

我是Angular2中的新手,并且在全局网络中,我想启动一个操作,在检查checkbox或更改Material-Design时使用Material-Design来更改数据库中的对象参数值尝试与[(ngModel)]但没有发生。这个想法是,我必须添加一些与checked | unchecked状态的命题,以确定它是否是truefalse命题。这里是命题模型在Angular2中检查复选框时启动一个事件

export class PropositionModel { 
     id:string; 
     wordingP:string; // the proposition 
     propStatus:Boolean; // the proposition status 
} 

这里是一个命题的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> 

这里添加命题的打字稿代码:

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();}) 
    } 

正如你所看到的我为默认为false,我希望在检查命题时对其进行更改。 这是一个图像,它如何寻找更好的问题理解。 enter image description here

任何帮助请吗?

回答

49

PLUNKER DEMO

模板:利用变化事件调用函数和传递事件。

<input type="checkbox" data-md-icheck (change)="addprop1($event)"/> 

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();}) 
    } 
} 
+1

请注意,它是(改变)和不(onChange)。这是我愚蠢的错误,花了我几分钟的时间来找出 –

+0

该笨拙的演示不起作用 – TomSlick

+0

感谢通知,修正:) –

4

您可以使用ngModel

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

要在你的代码更新财产checkboxValue当复选框被用户addProp()改变被称为更新的复选框状态。

+0

没有工作,对不起,您能否根据上面的代码澄清更多? –

+1

'[ngModel] =“checkboxValue”'添加'ngModel'方向和默认'ControlValueAccessor'(并将checkboxValue的值绑定到复选框)。使用'ngModel',我们可以绑定到每当复选框更改时发出的'ngModelChange'事件。 –

+1

你使用的是什么Angular“'2版本。在FF和IE中有一些绑定到输入元素的问题,但是他们最近修复了。 –

7

如果您将双重pamentalhesis添加到ngModel引用,您将获得对模型属性的双向绑定。该属性可以在事件处理程序中读取和使用。在我看来,这是最干净的方法。

<input type="checkbox" [(ngModel)]="myModel.property" (ngModelChange)="processChange()" /> 
相关问题