[英]How do we set default value to a radio button or set radion button as checked in angular?
如果来自 API 请求的ssoEnabled
不为空并且具有值,例如值为“是”,默认情况下应选中单选按钮是,如果值为否,则默认情况下应选中单选按钮“否”。
我们如何在角度上做到这一点? 喜欢根据 API 中的值提供或设置默认选中的 mat 单选按钮吗?
getUserData() {
this.isInProgress = true;
this.userService
.getUserData(this.userId)
.pipe(finalize(() => (this.isInProgress = false)))
.subscribe({
next: (res) => {
if (res.isSuccess) {
this.data = res.data;
this.ssoEnabled = this.data.ssoEnabled
}
},
error: (err) => this._notificationService.showError(err),
complete: noop,
});
}
<mat-radio-group formControlName="ssoEnabled" class="label3" >
<mat-card fxLayoutAlign="start center" style="cursor: pointer;"
[ngClass]="securityForm.get('ssoEnabled').value === 'Yes' ? 'selected-card' : ''">
<mat-radio-button color="accent" [value]="this.data.ssoEnabled"
[ngClass]="securityForm.get('ssoEnabled').value === 'Yes' ? 'selected-radio' : ''">
Yes
</mat-radio-button>
</mat-card>
<mat-card fxLayoutAlign="start center" style="cursor: pointer;"
[ngClass]="securityForm.get('ssoEnabled').value === 'No' ? 'selected-card' : ''">
<mat-radio-button value="this.data.ssoEnabled" color="accent"
[ngClass]="securityForm.get('ssoEnabled').value === 'No' ? 'selected-radio' : ''">
No
</mat-radio-button>
</mat-card>
</mat-radio-group>
所有无线电都应该共享指向模型中相同变量的相同 ngModel ( [ngModel]="ssoEnabled"
)。 默认值将是您在声明时设置的值( this.ssoEnabled = true;
)
这是一个简单的例子:
在 component.ts 中:
ssoEnabled = 'Yes'
在模板中:
<mat-radio-group [(ngModel)]="ssoEnabled">
<mat-radio-button [value]="'Yes'" [checked]="ssoEnabled === 'Yes'">{{
ssoEnabled
}}</mat-radio-button>
<mat-radio-button [value]="'No'" [checked]="ssoEnabled === 'No'">{{
ssoEnabled
}}</mat-radio-button>
</mat-radio-group>
*标签显示值用于演示目的。
在你的 module.ts 中:
imports: [
BrowserModule,
BrowserAnimationsModule,
MatRadioModule,
FormsModule
],
您也可以使用布尔值代替“是”和“否”字符串,具体取决于您希望在表单中具有什么值。
要将布尔值显示为“是”或“否”,您可以制作一个简单的管道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.