我一直在嘗試解決這個問題一段時間,也許你們中的一些人有答案。練習很簡單,我試圖在*ngFor回圈中創建一個輸入。
但是單選按鈕不能這樣作業......
TS Code:
get datas(): {radio:number}[] {
return [
{radio: 1},
{radio: 2},
{radio: 3},
{radio: 4},
{radio: 5},
{radio: 6},
]
}
ngOnInit() {
this.testForm = this.fb.group({
radios: [1]
});
}
change(val: number): void {
this.testForm.get('radios')?.setValue(val);
}
我已經編造了這種change方法,因此我可以重現單選選項更改。
HTML Code:
<form [formGroup]="testForm">
<ng-container *ngFor="let data of datas">
<input type="radio" [value]="data.radio" [name]="'radios'" [formControlName]="'radios'">
</ng-container>
other
<input type="radio" [value]="4" [name]="'radios'" [formControlName]="'radios'">
<input type="radio" [value]="5" [name]="'radios'" [formControlName]="'radios'">
<input type="radio" [value]="6" [name]="'radios'" [formControlName]="'radios'">
</form>
{{ testForm.value | json }}
不知道為什么other無線電輸入有效,但不是上述輸入。我也試過了[attr.value],但在這種情況下它沒有用,甚至會破壞更多東西。
uj5u.com熱心網友回復:
當您每次發生更改時都使用 get datas 時,它會一次呼叫 get datas。這是生成無法匹配任何舊物件的全新物件。你可以試試這個
// change from:
// get datas(): {radio:number, id: number}[] {
// return [
// {radio: 1},
// {radio: 2},
// {radio: 3},
// {radio: 4},
// {radio: 5},
// {radio: 6},
// ]
// }
// to:
datas = [
{ radio: 1 },
{ radio: 2 },
{ radio: 3 },
{ radio: 4 },
{ radio: 5 },
{ radio: 6 },
];
或這個
sampleData = [
{ radio: 1 },
{ radio: 2 },
{ radio: 3 },
{ radio: 4 },
{ radio: 5 },
{ radio: 6 },
];
get datas(): { radio: number }[] {
// console.log(1); <= unrem to check when it call
return this.sampleData;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/510115.html
