Angular 4 - 在里面使用ngModel(点击)

时间:2017-10-30 23:57:59

标签: javascript angular

所以我有以下html:

<div class="workflow-row">
    <input type="checkbox" id="new-workflow" [(ngModel)]="new_checkbox"> 
    <label>New Workflow</label>
    <input type="text" *ngIf="new_checkbox" placeholder="Enter Workflow Name">
</div>  
<div class="workflow-row">
    <input type="checkbox" id="edit-workflow" [(ngModel)]="edit_checkbox"> 
    <label>Edit Workflow</label>
    <select *ngIf="edit_checkbox"></select>
</div>

我希望复选框的行为类似于单选按钮,即:如果选中一个,则另一个变为未选中角度为4.我试过

<input type="checkbox" id="edit-workflow" (click)="new_checkbox.checked = false" 
[(ngModel)]="edit_checkbox">

但是我收到一个错误,它说new_checkbox是未定义的。奇怪的是,new_checkboxedit_checkbox ngIf 语句中工作,但不在(click)内部。我做错了什么?

2 个答案:

答案 0 :(得分:1)

我建议你尝试以下方法:

<强> component.ts:

export class AppComponent {
    edit_checkbox = false;
    new_checkbox = true;

    dropNewValue() {
        this.new_checkbox = false;
    }

    dropEditValue() {
        this.edit_checkbox = false;
    }
}

然后在您的模板文件中,例如 component.html ,将您的模板稍微更改为:

<div class="workflow-row">
    <input type="checkbox" id="new-workflow" [(ngModel)]="new_checkbox" (ngModelChange)="dropEditValue()">
    <label>New Workflow</label>
    <input type="text" *ngIf="new_checkbox" placeholder="Enter Workflow Name">
</div>
<div class="workflow-row">
    <input type="checkbox" id="edit-workflow" [(ngModel)]="edit_checkbox" (ngModelChange)="dropNewValue()">
    <label>Edit Workflow</label>
    <select *ngIf="edit_checkbox"></select>
</div>

我刚试过这个并且它有效。但是我建议切换到单选按钮方法,因为您将获得开箱即用的相同行为。

答案 1 :(得分:0)

不要像你一样写Angular而不是经常写javascript而不是

(click)="new_checkbox.checked = false"

做类似

的事情
// .html
(click)="uncheckNewCheckbox()"

// .js or .ts
uncheckNewCheckbox() {
  this.new_checkbox.checked = false;
}