使用Angular 2+检查单选按钮时如何隐藏元素?

时间:2017-09-27 00:34:05

标签: angular

我目前正在尝试使用clickngIf*来执行此操作,但只有双击才会发生更改。此外,如果我双击当前选择的选项,视图将会更改,我不希望这种情况发生。我该怎么做呢?

      <fieldset class="form-group col-md-3">
    <div class="form-check">
      <label class="form-check-label">
        <input (click)="computation = !computation" type="radio" class="form-check-input" name="optionsRadios" id="optionsRadios1" value="option1" checked>
          Enable View
      </label>
    </div>
    <div class="form-check">
    <label class="form-check-label">
        <input (click)="computation = !computation" type="radio" class="form-check-input" name="optionsRadios" id="optionsRadios2" value="option2">
          Disable View
      </label>
    </div>
  </fieldset>
  <div *ngIf="computation" class="form-group col-md-3">
    <label for="app_id_org_input">Enabled</label>
    <input type="text" class="form-control" id="app_id_org_input" placeholder="Enabled">
  </div>
  <div *ngIf="!computation" class="form-group col-md-3">
    <label for="app_id_input">Disabled</label>
    <input type="text" class="form-control" id="app_id_input" placeholder="Disabled">
  </div>

1 个答案:

答案 0 :(得分:1)

我有另一种方法可以帮助你实现这一目标。您可以使用ngModel让Angular2更改变量值。这是适合我的代码。 在你的班上,

// set your variable
private computation = true;

在您的模板中

  <fieldset class="form-group col-md-3">
    <div class="form-check">
      <label class="form-check-label">
        <input type="radio" class="form-check-input" name="optionsRadios" id="optionsRadios1" [value]="true" checked [(ngModel)]="computation">
          Enable View
      </label>
    </div>
    <div class="form-check">
    <label class="form-check-label">
        <input type="radio" class="form-check-input" name="optionsRadios" id="optionsRadios2" [value]="false" [(ngModel)]="computation">
          Disable View
      </label>
    </div>
  </fieldset>
  <div *ngIf="computation" class="form-group col-md-3">
    <label for="app_id_org_input">Enabled</label>
    <input type="text" class="form-control" id="app_id_org_input" placeholder="Enabled">
  </div>
  <div *ngIf="!computation" class="form-group col-md-3">
    <label for="app_id_input">Disabled</label>
    <input type="text" class="form-control" id="app_id_input" placeholder="Disabled">
  </div>