[英]Default radio button select value angular material 2
我正在按照本文檔處理角度材料 2 單選按鈕: https : //material.angular.io/components/component/radio 。
我面臨的問題是讓單選按鈕的默認選擇值為No
。 如果您在 plunker 中看到: https ://plnkr.co/edit/jdRxVLdSfFqR4XOdpyUN ? p = preview,您會發現沒有選擇任何選項。 我希望頁面加載時默認值為No
。
許多 plunkrs 似乎不再為我工作。 這里有一個修改過的stackblitz:
如前所述,我們可以設置 ngModel 和變量:
[(ngModel)]="favoriteSeason"
並在“ts”文件中:
favoriteSeason: string = 'Winter';
或者我們可以設置選中的:
[checked]="season === 'Winter'"
我最近發現的另一個小問題是,如果您錯誤地將 mat-checkbox 設置為不正確(重復 ID),則它不起作用 - 您無法檢查任何內容。 確保您的 ID 是唯一的。
您可以使用checked
,如下所示:
[checked]="data.value ==='false'"
請注意,我們正在使用字符串'false'
而不是false
進行檢查,因為您的值具有值為false
的字符串。
您可以使用[checked]
屬性來實現它。 看到這個Plunker
還有另一個選項是您可以使用[(ngModel)]
用您的組件初始化md-radio-group
。
plunker演示。
我喜歡使用材料單選按鈕時的反應式方法。 下面是一個示例,說明如何使用數據庫檢查特定 formControlName 的真假
對話框中的組件
<mat-radio-group formControlName="trueClient">
<mat-radio-button class="material-radio" value="true" [checked]="data.trueClient === 'true'">True Client</mat-radio-button>
<mat-radio-button class="material-radio" value="false" [checked]="data.lostLead === 'false'">Lost Lead</mat-radio-button>
</mat-radio-group>
如果這是更新表單,請確保在表單構建器中設置值。 下面的例子:
對話框中組件的 .ts 文件。
this.viewClient.setValue({
trueClient: this.data.trueClient
});
在這種情況下,我在對話框中打開數據。 所以數據來自以下: component.ts 之前打開對話框。 只是一個參考,以便您知道我從哪里獲得數據變量來設置值。
用於打開對話框的組件。 有關如何設置的更多信息,請參考材料文檔中的對話框。
const dialogRef = this.dialog.open(ClientNotesComponent, {
height: '600px',
width: '800px',
data: {trueClient: trueClient}
});
});
}
<mat-radio-button [checked]="true"</mat-radio-button>
HTML文件
<mat-radio-group aria-label="Select an option" [(ngModel)]="formValues['type']">
<mat-radio-button value="individual">Individual</mat-radio-button>
<mat-radio-button value="business">Business</mat-radio-button>
</mat-radio-group>
ts文件
ngOnInit()
{
this.formValues['type'] = "business";
}
在我的情況下,選擇問題已通過將name="howLong"
屬性替換為[ngModelOptions]="{standalone: true}"
。
需要注意的是,選擇工作了A day or less than a day
。 但它沒有工作More than a day
非工作版本:
<mat-radio-group
[(ngModel)]="howLong"
name="howLong"
(change)="resetTime()">
<mat-radio-button class="ignore" value="MoreThanADay">
More than a day
</mat-radio-button>
<mat-radio-button value="ADayOrLessThanADay">A day or less than a day</mat-radio-button>
</mat-radio-group>
工作版本:
<mat-radio-group
[(ngModel)]="howLong"
[ngModelOptions]="{standalone: true}"
(change)="resetTime()">
<mat-radio-button class="ignore" value="MoreThanADay">
More than a day
</mat-radio-button>
<mat-radio-button value="ADayOrLessThanADay">A day or less than a day</mat-radio-button>
</mat-radio-group>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.