简体   繁体   English

Angular 4-在内部使用ngModel(单击)

[英]Angular 4 - using ngModel inside (click)

So I have the following html: 所以我有以下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>

I want the checkboxes to act like radio buttons, ie: if one is checked, the other one becomes unchecked with angular 4. I tried doing 我希望复选框的作用类似于单选按钮,即:如果选中了一个,则另一个将变为不带有角度4的复选框。

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

but I get an error and it says that new_checkbox is undefined. 但是我得到一个错误,它说new_checkbox是未定义的。 The weird thing is that new_checkbox and edit_checkbox work inside the ngIf statements but not inside the (click) 's. 奇怪的是, new_checkboxedit_checkboxngIf语句中起作用 ,而不在(click)的内部起作用 What am I doing wrong? 我究竟做错了什么?

I suggest you to try the following: 我建议您尝试以下方法:

component.ts: component.ts:

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

    dropNewValue() {
        this.new_checkbox = false;
    }

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

Then in your template file, eg component.html , change your template slightly to: 然后在您的模板文件中,例如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>

I've just tried this and it works. 我刚刚尝试过,它可以工作。 However I do recommend to switch to radio buttons approach, because you will get the same behavior out of the box. 但是,我建议您切换到单选按钮方法,因为您将获得相同的行为。

Don't write Angular like you're writing regular javascript instead of 不要像编写普通的javascript一样写Angular

(click)="new_checkbox.checked = false"

do something like 做类似的事情

// .html
(click)="uncheckNewCheckbox()"

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM