【问题标题】:How to set radio button selected by default in angular 8?如何在 Angular 8 中设置默认选中的单选按钮?
【发布时间】:2023-03-04 23:54:01
【问题描述】:

我对 Angular 8 技术非常陌生,并且在设置默认选中的单选按钮之一时遇到了一些问题。

我已尝试添加其中一些属性[checked]="true", checked,但问题仍然相同。

HTML

<div class="form-check">
    <mat-radio-button type="radio" id="materialUnchecked" name="filterType" 
        value="0" [(ngModel)]="filterType" [checked]="true">
        By client
    </mat-radio-button>

    <mat-radio-button type="radio" id="materialChecked" name="filterType" 
        value="1" [(ngModel)]="filterType">
        By student
    </mat-radio-button>
    <br><br>
</div>

TS

protected filterType;

任何帮助将不胜感激。谢谢

【问题讨论】:

标签: angular


【解决方案1】:

为变量设置默认值并像下面这样使用
这里我使用了flag作为默认变量

TS

 import { Component } from '@angular/core';

    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      name = 'Angular';
      flag: any;
      constructor() {
        this.flag = 0;
      }
    }

HTML

<input type="radio" name="1" id="1" class="with-gap" [(ngModel)]="flag" [value]="0">
<input type="radio" name="2" id="2" class="with-gap" [(ngModel)]="flag" [value]="1" >
{{flag}}

这是 stackblitz 网址

https://stackblitz.com/edit/angular-dyy5y8

【讨论】:

    【解决方案2】:

    在您的 ngOnInit 中将 filterType 值设置为 true。

    this.filterType=1;

    【讨论】:

      猜你喜欢
      • 2018-06-26
      • 2021-01-06
      • 2017-10-02
      • 2015-12-10
      • 1970-01-01
      • 1970-01-01
      • 2020-10-30
      • 2018-04-21
      • 2016-10-30
      相关资源
      最近更新 更多