【问题标题】:Conditionally tick the checkbox in modal dialog in Angular有条件地勾选 Angular 模态对话框中的复选框
【发布时间】:2017-11-03 16:44:48
【问题描述】:

我有一个引导模式对话框,其中包含一些复选框。每个复选框代表数据库中的一个类别,只有当用户对该类别感兴趣时,我才需要勾选该复选框。

以下是我的模态html

<div *ngIf="_user" id="categoryModal" class="modal fade" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">

            <div class="modal-body" id="categoryDiv">
                <div class="row">
                  <div *ngIf="_tenderCategories">
                    <span *ngFor="let category of _tenderCategories; let i = index;">
                        <div class="col-md-4">
                            <div class="checkbox">
                                <label>
                                    <input id={{category.id}} type="checkbox" class="category-checkbox" [checked]="isUserInterested(category)" (change)="onCategoryCheckBoxClick(category)">
                                    <p class="tender-category" style="cursor: pointer;">{{category.name}}</p>

                                </label>
                            </div>
                        </div>
                    </span>
                  </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Submit</button>
            </div>
        </div>

    </div>
</div>

如您所见,为了勾选复选框,我调用了函数isUserInterested(category)

我面临的问题是,当页面仅重新加载时,我提到的函数会被调用。当我单击 html 页面上的链接时,会出现上面的模式;但在这种情况下不会调用该函数。当我单击上述链接时,该组件已拥有执行该功能所需的所有数据。

isUserInterested(category: Category) {
   if (this._user.interestedCategories.indexOf(category) > -1) {
     // if the _user.interestedCategories list contaians the category, that category should be shown as marked
     console.log("Category "+category.id+" interested");
     return true;
   } else {
     return false;
   }
  }

为什么我没有得到预期的行为?我怎样才能以我期望的方式实现它?

【问题讨论】:

    标签: javascript twitter-bootstrap angular checkbox


    【解决方案1】:

    您应该使用ngModel 来实现这一点,如下所示,

    <input id={{category.id}} type="checkbox" class="category-checkbox" 
        [ngModel]="isUserInterested(category)" 
        (ngModelChange)="onCategoryCheckBoxClick(category)">
    

    更新 1:在模态对话框中

    子模型应包含users 对象,如下所示,

     @Input() users?:any[];
    

    方法如下

    isUserInterested(c){
          if(this.category.interestedCat.indexOf(c) > -1){
            console.log(c)
            return true;
          }
          else {
    
            return false
          }
        }
    

    Updated LIVE DEMO

    【讨论】:

    • 应用程序显示相同的行为。如果复选框在页面中,这将起作用。但是我的复选框在一个模式对话框中,只有当用户点击页面上的链接时才会出现
    • @vigamage 在这种情况下,您应该在子组件中拥有完整的用户对象以检查条件。检查更新的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 2017-10-17
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 2014-03-12
    相关资源
    最近更新 更多