【问题标题】:Angular 5 how to get the checkboxes valuesAngular 5如何获取复选框值
【发布时间】:2018-09-25 10:34:19
【问题描述】:

我有一个复选框列表,我想在提交表单时获取复选框的值。我看到以下问题:

1) 当我点击一个复选框时,所有复选框都会被选中。

2) ' purpose' 字段的值在控制台显示“真”或“假”,取决于选择。

<article class="mb-2 mb-md-4">
        <header class="border-bottom mb-3">
            <h6 class="mb-3"><i aria-hidden="true" class="fa fa-chevron-circle-right mr-2 text-primary"></i>Purpose of Claim</h6>
            <br> The Claim is made against the carrier for:
            <br> (Please tick as appropriate)
        </header>
        <label class="custom-check text-left flex-row">
            <input type="checkbox" id="Loss" value="Loss" name="purpose" [(ngModel)]="purpose" ><span class="checkmark"></span><strong class="font-weight-medium pl-2">Loss</strong>
        </label>
        <label class="custom-check text-left flex-row">
            <input type="checkbox" id="Damage" value="Damage" name="purpose" [(ngModel)]="purpose"><span class="checkmark"></span><strong class="font-weight-medium pl-2">Damage</strong>
        </label>
        <label class="custom-check text-left flex-row">
            <input type="checkbox" id="Incomplete" value="Incomplete" name="purpose" [(ngModel)]="purpose" ><span class="checkmark"></span><strong class="font-weight-medium pl-2">Incomplete
                Item</strong>
        </label>
    </article>

【问题讨论】:

  • 因为您对所有复选框使用相同的变量,即目的
  • 如果你不为每个变量使用相同的变量,而是为每个变量提供它自己的值,你可以从你的 ViewModel 那里读取它们。否则,您可以使用 ViewChildren .. 但只需从模型中读取。通常你会在你的模型上循环, *ngFor="..."
  • @StefanRein 你能解释一下你的答案吗?

标签: angular angular5


【解决方案1】:

在课堂上:

@Component(..)
class FooComponent {
    public items: Array<{purpose: boolean}> = [
        {purpose: true},
        {purpose: false},
        {purpose: true},
        {purpose: false}
    ];
}

模板:

<div *ngFor="let item of items; let i = index">
    <input type="checkbox" name="name-{{i}}" [(ngModel)]="item.purpose" />
</div>

<pre>
    {{items | json}}
</pre>

【讨论】:

    【解决方案2】:

    在 html 和类调用中使用表单标签:form.controls['purpose'].value;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-03
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      相关资源
      最近更新 更多