[英]ngModel in input radio?
我正在使用 Angular 6 開發應用程序。我遇到了一個大問題。 使用模板驅動的表單,我希望可以在按下提交按鈕時發送在單選按鈕中選擇的項目。 當我使用<input type="text" [(ngModel)] = "value" />
( value
是我組件的數據字段)時沒問題,但是如果我嘗試這樣做:
<div class="form-group">
<div *ngFor = "let option of options">
<div class="radio">
<input type = "radio"
name = "radio"
[(ngModel)] = "value"
/>
<label for="{{option.id}}">{{option.id}}</div>
</label>
</div>
</div>
</div>
結果是bug! 我什至無法通過移動選擇器來單擊多個按鈕! 一切都被卡住了! 顯然它不適用於表單。 如果我以圖形方式刪除[(ngModel)] = "value"
它可以工作,但如果沒有 ngModel 指令,如果我在使用 (ngSubmit) 的模板驅動表單中輸入此代碼,則它不起作用。 非常感謝。
您缺少每個單選按鈕的值,因此綁定無法正常工作。 它無法確定應該檢查哪個輸入,因此它們都沒有被檢查。 將模板更新為如下所示:
<div *ngFor="let option of options">
<div class="radio">
<input type="radio"
name="radio"
id="radio-{{option.id}}"
[(ngModel)]="value"
[value]="option.value"
/>
<label for="radio-{{option.id}}">{{option.id}}
</label>
</div>
單選按鈕的工作方式不同。 需要添加一個value
以使其工作。 如果要從角度分配值,請使用[value]
。
我已經讓它在stackblitz 的一個例子中運行:
<div class="form-group">
<div *ngFor="let option of options; let i=index">
<div class="radio">
<input type="radio" id="{{option.id}}" name="radio{{i}}" [(ngModel)]="option.value" [value]="option.id" />
<label for="{{option.id}}">{{option.id}}</label>
</div>
</div>
</div>
<hr>
<h2>Values for options</h2>
<ul>
<ng-container *ngFor="let option of options; let i=index">
<li *ngIf="option.value !== ''">Value for {{option.id}}: {{option.value}}</li>
</ng-container>
</ul>
成分
value: any;
options = [
{
id: "test1",
value: ''
},
{
id: "test2",
value: ''
},
{
id: "test3",
value: ''
}];
擴展/提示:
您甚至可以使用[(ngModel)] = "value"
將最后選擇的值分配給value
。
為這些單選按鈕指定相同的名稱name="radio"
以確保只能選擇該組中的一個。
在 ts 文件中:
radio_button_value = null;
box_options = [
{
"name": "Word",
"value": "word",
},
{
"name": "Line",
"value": "line"
},
]
在 html 文件中:
請注意標簽“名稱”,這將是我們在另一個 for 循環中非常關注的問題。
<div *ngFor="let box_opt of box_options; let i=index">
<input name="option-{{i}}" type="radio" [value]="box_opt.value" [(ngModel)]="radio_button_value">
{{box_opt.name}}
<br>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.