簡體   English   中英

Angular 4-在內部使用ngModel(單擊)

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

所以我有以下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_checkboxngIf語句中起作用 ,而不在(click)的內部起作用 我究竟做錯了什么?

我建議您嘗試以下方法:

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>

我剛剛嘗試過,它可以工作。 但是,我建議您切換到單選按鈕方法,因為您將獲得相同的行為。

不要像編寫普通的javascript一樣寫Angular

(click)="new_checkbox.checked = false"

做類似的事情

// .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