![](/img/trans.png)
[英]Passing reactive form value to another component on button click in angular
[英]ngIf an angular reactive form component value
我有一组单选按钮。 如果用户选择值“是”,我想在表单上显示一个附加框。
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>
任何人都可以让它工作并告诉我我在这里做错了什么吗?
您在模板中编写的所有内容都针对相应的 class(或针对模板变量)进行解析,因此您必须像这样参考 JavaScript 控件:
*ngIf="form.controls['selectedButton'].value === 'yes'"
调用 function 根据单选按钮的值设置标志, (ngModelChange)="onRadiochange($event)"
试试这样:
.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" />
Whenever yes checkbox is selected, you have to display the title textbox.
在这种情况下,请像这样更改您的代码。
在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>
这些更改仅在选择“是的复选框”框时显示标题文本框。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.