ng如果角反应形式的成分值

时间:2019-11-15 13:18:45

标签: javascript angular typescript angular-reactive-forms

我有一组单选按钮。如果用户选择值“是”,我想在表单上显示一个附加框。

https://stackblitz.com/edit/angular-4bgahw?file=src/app/personal/personal.component.ts

HTML.component

<div formGroupName="radioButtonsGroup" class="form-group col-6 pl-0 pt-3">

    <div class="form-check-inline" *ngFor="let item of personal.radioButtonsdata">
        <label for="{{item.section}}" class="col-12 customradio"
            ><span>{{item.section}}</span>
            <input [value]="item" id="{{item.section}}" type="radio" formControlName="selectedButton"/>
            <span class="checkmark"></span>
        </label>
    </div>

    <!-- <div class="col-md-8" *ngIf="selectedButton.control.item === 'yes'"> --> //my attempt to target above input value
  <div class="col-md-8" >
        <input type="text" formControlName="title" class="form-control" placeholder="Title">
</div>
    </div>

有人可以让这个工作并在这里告诉我我在做什么错吗?

4 个答案:

答案 0 :(得分:1)

您在模板中编写的所有内容都会根据相应的类(或模板变量)进行解析,因此您必须像这样引用JavaScript控件:

*ngIf="form.controls['selectedButton'].value === 'yes'"

答案 1 :(得分:1)

调用一个函数以根据单选按钮(ngModelChange)="onRadiochange($event)"的值设置标志

尝试这样:

Working Demo

.html

<input [value]="item" (ngModelChange)="onRadiochange($event)" id="{{item.section}}" type="radio" formControlName="selectedButton" />

<div class="col-md-8" *ngIf="showTitle">
        <input type="text" formControlName="title"   class="form-control" placeholder="Title">
</div>

.ts

  onRadiochange(e) {
    if(e.section == 'yes'){
      this.showTitle = true
    } else {
      this.showTitle = false
    }
  }

也可以这样一行完成:

<input [value]="item" (ngModelChange)="$event.section == 'yes' ? showTitle=true:showTitle=false" id="{{item.section}}" type="radio" formControlName="selectedButton" />

答案 2 :(得分:1)

您需要访问表单控件的值:

class ApplicationRecord < ActiveRecord::Base

STACKBLITZ

答案 3 :(得分:1)

只要选择复选框,就必须显示标题文本框。
在这种情况下,请像这样更改代码。

personal.component.ts 中,添加此变量。

yesSelected: boolean = true;

也在ngOnInit()中,

this.form.valueChanges.subscribe(val=>{
      if(val.radioButtonsGroup.selectedButton.section === "yes") 
         this.yesSelected = true;
      else 
         this.yesSelected = false;
});

personal.component.html 中,重写您的if条件。

<div class="col-md-8" *ngIf="yesSelected">
      <input type="text" formControlName="title" placeholder="Title">
</div>

仅当选中“是”复选框时,这些更改才会显示标题文本框。