Angular2 - การผูกปุ่มวิทยุ


120

ฉันต้องการใช้ปุ่มตัวเลือกในรูปแบบโดยใช้ Angular 2

Options : <br/>

1 : <input name="options" ng-control="options" type="radio" value="1"  [(ng-model)]="model.options" ><br/>

2 : <input name="options" ng-control="options" type="radio" value="2" [(ng-model)]="model.options" ><br/>

model.options ค่าเริ่มต้นคือ 1

เมื่อโหลดเพจแล้วจะไม่มีการตรวจสอบปุ่มตัวเลือกแรกและการปรับเปลี่ยนจะไม่เชื่อมโยงกับโมเดล

ความคิดใด ๆ ?


1
ตัวอย่างรายการวิทยุไดนามิกที่นี่freakyjolly.com/how-to-show-radio-input-listing-in-angular-6
Code Spy

คำตอบ:


108

ใช้[value] = "1"แทนvalue = "1"

<input name="options" ng-control="options" type="radio" [value]="1"  [(ngModel)]="model.options" ><br/>

<input name="options" ng-control="options" type="radio" [value]="2" [(ngModel)]="model.options" ><br/>

แก้ไข:

ตามที่แนะนำโดย thllbrg "สำหรับเชิงมุม 2.1+ ให้ใช้[(ngModel)]แทน[(ng-model)]"


7
วัตถุประสงค์ของแอตทริบิวต์การควบคุม ng คืออะไร? ดูเหมือนทุกอย่างจะทำงานได้โดยไม่ต้องใช้มัน
พระคุณเจ้า

4
ใน Angular 4+ คุณต้องใช้[(ngModel)]แทน[(ng-model)]ไฟล์. อ่านอีกครั้ง .
Claudio Holanda

1
สิ่งนี้ใช้ได้เฉพาะกับการเพิ่มโหมดใหม่ ไม่ทำงานสำหรับโหมดแก้ไข ฉันไม่พบว่าอะไรคือเหตุผล ในค่าที่กำหนดแบบเปิดใหม่สำหรับโมเดลที่ทำงาน แต่ไม่ทำงานเมื่อฉันดึงค่าจากเซิร์ฟเวอร์และแสดงในหน้าจอ แต่ถ้าฉันแสดงในค่าฉลากแสดง แต่ไม่ได้ตรวจสอบ
Vinoth Kumar

4
ในกรณีของฉันฉันใช้value="1" [(ngModel)]="model.options". การใส่valueวงเล็บเหลี่ยมไม่ทำงาน
Sylvan D Ash

2
แปลก แต่ในกรณีของฉันฉันต้องใช้ value = "1" แทน [value] = "1" ฉันใช้ Angular 6
codingbbq

61

หมายเหตุ - การผูกปุ่มตัวเลือกเป็นคุณสมบัติที่รองรับใน RC4 เป็นต้นไป - ดูคำตอบนี้

ตัวอย่างปุ่มตัวเลือกโดยใช้ RadioControlValueAccessor ที่กำหนดเองคล้ายกับ CheckboxControlValueAccessor ( อัปเดตด้วย Angular 2 rc-1 )

App.ts

import {Component} from "@angular/core";
import {FORM_DIRECTIVES} from "@angular/common";
import {RadioControlValueAccessor} from "./radio_value_accessor";
import {bootstrap} from '@angular/platform-browser-dynamic';

@Component({
    selector: "my-app",
    templateUrl: "template.html",
    directives: [FORM_DIRECTIVES, RadioControlValueAccessor]
})
export class App {

    model;

    constructor() {
        this.model = {
            sex: "female"
        };
    }
}

template.html

<div>
    <form action="">
        <input type="radio" [(ngModel)]="model.sex"  name="sex" value="male">Male<br>
        <input type="radio" [(ngModel)]="model.sex"  name="sex" value="female">Female
    </form>

    <input type="button" value="select male" (click)="model.sex='male'">
    <input type="button" value="select female" (click)="model.sex='female'">
    <div>Selected Radio: {{model.sex}}</div>
</div>

radio_value_accessor.ts

import {Directive, Renderer, ElementRef, forwardRef} from '@angular/core';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from '@angular/common';

export const RADIO_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => RadioControlValueAccessor),
    multi: true
};

@Directive({
   selector:
       'input[type=radio][ngControl],input[type=radio][ngFormControl],input[type=radio][ngModel]',
   host: {'(change)': 'onChange($event.target.value)', '(blur)': 'onTouched()'},
   bindings: [RADIO_VALUE_ACCESSOR]
})
export class RadioControlValueAccessor implements ControlValueAccessor {
   onChange = (_) => {};
   onTouched = () => {};

   constructor(private _renderer: Renderer, private _elementRef: ElementRef) {}

   writeValue(value: any): void {
       this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', value == this._elementRef.nativeElement.value);
   }
   registerOnChange(fn: (_: any) => {}): void { this.onChange = fn; }
   registerOnTouched(fn: () => {}): void { this.onTouched = fn; }
}

ที่มา: https://github.com/angular2-school/angular2-radio-button

Plunker live สาธิต: http://plnkr.co/edit/aggee6An1iHfwsqGoE3q?p=preview


4
ในทำนองเดียวกันคำถามควรมีรหัสที่เกี่ยวข้องในคำถามคำตอบก็ควรมีเช่นกัน สิ่งนี้อาจตอบคำถามได้ในทางทฤษฎี แต่ควรรวมส่วนสำคัญของคำตอบไว้ที่นี่สำหรับผู้ใช้ในอนาคตและระบุลิงก์สำหรับอ้างอิง ตอบ Link-dominatedสามารถกลายเป็นที่ไม่ถูกต้องผ่านลิงก์เสีย
Mogsdad

เยี่ยมมาก .. มันแปลกที่มันไม่รวมอยู่ในเฟรม
เวิร์ค

ทางออกที่ดี! การเพิ่มเล็กน้อย: ฉันใช้อินพุต css [type = "radio"]: ตรวจสอบรูปแบบ แต่ใช้ได้เฉพาะกับฉันเมื่อใช้ nativeElement ของ _elementRef แทนที่จะเป็น _elementRef: this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', value == this._elementRef.nativeElement.value);
bas

2
@GregWoods อัปเดตโพสต์ด้วยการเปลี่ยนแปลงใหม่และขอบคุณสำหรับคำขอให้ดึง
Nidin Vinayakan

1
ตอนนี้ได้รับการสนับสนุนโดยกำเนิดโดยใช้ angular rc4 ขึ้นไป
Ckln

45

วิธีแก้ปัญหาด้วยตนเองของฉันซึ่งเกี่ยวข้องกับการอัปเดตด้วยตนเองmodel.optionsเมื่อเลือกปุ่มตัวเลือกใหม่:

template: `
  <label *ngFor="let item of radioItems">
    <input type="radio" name="options" (click)="model.options = item" 
     [checked]="item === model.options">
    {{item}}
  </label>`

class App {
  radioItems = 'one two three'.split(' ');
  model      = { options: 'two' };
}

สิ่งนี้Plunkerแสดงให้เห็นข้างต้นตลอดจนวิธีใช้ปุ่มเพื่อเปลี่ยนปุ่มตัวเลือกที่เลือกนั่นคือเพื่อพิสูจน์ว่าการเชื่อมโยงข้อมูลเป็นแบบสองทาง:

<button (click)="model.options = 'one'">set one</button>

ฉันมีสองคำถาม แรก: ในget debug()ฟังก์ชันgetย่อมาจากอะไร? ประการที่สองคือ: มีทางเลือกอื่นเช่นคำตอบนี้สำหรับช่องทำเครื่องหมายหรือไม่? โปรดระบุรหัสสำหรับช่องทำเครื่องหมายด้วย ขอบคุณ +1 สำหรับคำตอบที่ดี
Pardeep Jain

2
@PardeepJain, getเป็นคุณลักษณะการเข้าถึง typescript โพสต์คำถามสำหรับช่องทำเครื่องหมาย
Mark Rajcok

สามารถส่งพารามิเตอร์ในลักษณะนี้ "{{debug (abc)}}" ได้หรือไม่
Pardeep Jain

1
@PardeepJain ดูplnkr.co/edit/iH3Te9EK7Y1dPXMzfWt6?p=preview คุณไม่สามารถเรียกตัวตั้งค่าเหมือนฟังก์ชันได้ดังนั้นAnotherdate('2015-05-18T02:30:56')จะไม่ทำงาน Setters จะถูกเรียกเมื่อคุณพยายามกำหนดค่าให้กับคุณสมบัติ ใน plunker ของฉันฉันสร้างsetDate()ฟังก์ชั่น \ hat Anotherdateยอมรับค่าวันใหม่ซึ่งกำหนดให้แล้ว การมอบหมายนั้นจะเรียกตัวเซ็ตเตอร์โดยอัตโนมัติ
Mark Rajcok

1
@PardeepJain {{}}การผูกจะได้รับการประเมินอีกครั้งทุกรอบการตรวจจับการเปลี่ยนแปลง ฉันติดตั้งngDoCheck()ใน AppComponent ใน plunker เพื่อนับรอบการตรวจจับการเปลี่ยนแปลง จากนั้นเราจะเห็นว่าการตรวจจับการเปลี่ยนแปลงถูกเรียก 3 ครั้ง ในโหมด dev การเชื่อมโยงจะถูกตรวจสอบสองครั้งดังนั้น 6 ครั้ง
Mark Rajcok

36

นี่คือวิธีที่ดีที่สุดในการใช้ปุ่มตัวเลือกใน Angular2 ไม่จำเป็นต้องใช้เหตุการณ์ (คลิก) หรือ RadioControlValueAccessor เพื่อเปลี่ยนค่าคุณสมบัติที่ผูกไว้การตั้งค่าคุณสมบัติ [การตรวจสอบ] จะทำการหลอกลวง

<input name="options" type="radio" [(ngModel)]="model.options" [value]="1"
       [checked]="model.options==1" /><br/>
<input name="options" type="radio"  [(ngModel)]="model.options" [value]="2"
       [checked]="model.options==2" /><br/>

ฉันเผยแพร่ตัวอย่างการใช้ปุ่มตัวเลือก: Angular 2: วิธีสร้างปุ่มตัวเลือกจาก enum และเพิ่มการผูกแบบสองทาง ใช้งานได้จาก Angular 2 RC5 เป็นอย่างน้อย


2
สิ่งนี้ใช้ได้เฉพาะกับการเพิ่มโหมดใหม่ ไม่ทำงานสำหรับโหมดแก้ไข ฉันไม่พบว่าอะไรคือเหตุผล ในค่าที่กำหนดแบบเปิดใหม่สำหรับโมเดลที่ทำงาน แต่ไม่ทำงานเมื่อฉันดึงค่าจากเซิร์ฟเวอร์และแสดงในหน้าจอ แต่ถ้าฉันแสดงในค่าฉลากแสดง แต่ไม่ได้ตรวจสอบ
Vinoth Kumar

1
@VinothKumar คุณจัดการให้โหมดแก้ไขทำงานได้หรือไม่? ฉันมีปัญหาเดียวกัน
Dave Nottage

18

ปัญหานี้ได้รับการแก้ไขแล้วในเวอร์ชัน Angular 2.0.0-rc.4 ตามลำดับในรูปแบบ

รวม"@angular/forms": "0.2.0"อยู่ใน package.json

จากนั้นขยาย bootstrap ของคุณใน main ส่วนที่เกี่ยวข้อง:

...
import { AppComponent } from './app/app.component';
import { disableDeprecatedForms, provideForms } from '@angular/forms';

bootstrap(AppComponent, [
    disableDeprecatedForms(),
    provideForms(),
    appRouterProviders
]);

ฉันมีสิ่งนี้ใน. html และทำงานได้อย่างสมบูรณ์: value: {{buildTool}}

<form action="">
    <input type="radio" [(ngModel)]="buildTool" name="buildTool" value="gradle">Gradle <br>
    <input type="radio" [(ngModel)]="buildTool" name="buildTool" value="maven">Maven
</form>

นี่คือคำตอบที่ถูกต้องสำหรับ rc4 และเพื่อเพิ่มวิทยุสามารถใช้กับ enums ได้
รอน

8
ใช้ RC7 ฉันต้องวางวงเล็บรอบ [value]
Brian Vander Plaats

1
ฉันคิดว่าคุณต้องใช้วงเล็บเพราะคุณใช้ตัวแปรของส่วนประกอบของคุณแทนสตริงในกรณีของฉันคำตอบของ @ Zolcsi ทำงานได้ดี!
Naeem Baghi

1
ส่วนนี้ด้วยdisableDeprecatedFormsและprovideFormsดูขลังและไม่สมเหตุสมผล สิ่งเหล่านี้ใช้ทำอะไร? นี่เป็นรหัสที่อ่านไม่ได้ซ้ำซ้อนซึ่งทำให้เกิดสิ่งที่ไม่สามารถคาดเดาได้ในระดับที่ไม่รู้จัก
Gherman

6

ฉันกำลังมองหาวิธีที่เหมาะสมในการจัดการปุ่มตัวเลือกเหล่านี้นี่คือตัวอย่างสำหรับวิธีแก้ปัญหาที่ฉันพบที่นี่:

<tr *ngFor="let entry of entries">
    <td>{{ entry.description }}</td>
    <td>
        <input type="radio" name="radiogroup" 
            [value]="entry.id" 
            (change)="onSelectionChange(entry)">
    </td>
</tr>

สังเกตonSelectionChangeที่ส่งผ่านองค์ประกอบปัจจุบันไปยังเมธอด


4

ดูเหมือนว่ายังไม่รองรับอินพุตวิทยุ ควรจะมีการเข้าถึงค่าที่ป้อนวิทยุ (คล้ายกับช่องทำเครื่องหมายของหนึ่งที่จะกำหนด 'ตรวจสอบ' attr ที่นี่ ) แต่ฉันไม่ได้พบใด ๆ ดังนั้นฉันจึงใช้หนึ่ง; คุณสามารถตรวจสอบมันออกมาที่นี่



@JimB: โชคร้ายที่มันปรากฏความหมายของคนพื้นเมืองที่มีแตกต่างกัน
Kiara Grouwstra


4

ต่อไปนี้แก้ไขปัญหาของฉันโปรดพิจารณาเพิ่มอินพุตวิทยุภายในformแท็กและใช้[value]แท็กเพื่อแสดงค่า

<form name="form" (ngSubmit)="">
    <div *ngFor="let item of options">
        <input [(ngModel)]="model.option_id" type="radio" name="options" [value]="item.id"> &nbsp; {{ item.name }}
    </div>
</form>

3

นี่คือวิธีแก้ปัญหาที่เหมาะกับฉัน มันเกี่ยวข้องกับการผูกปุ่มตัวเลือก - แต่ไม่ผูกมัดกับข้อมูลทางธุรกิจ แต่จะผูกกับสถานะของปุ่มตัวเลือกแทน อาจไม่ใช่ทางออกที่ดีที่สุดสำหรับโครงการใหม่ แต่เหมาะสำหรับโครงการของฉัน โปรเจ็กต์ของฉันมีโค้ดที่มีอยู่จำนวนมากที่เขียนด้วยเทคโนโลยีอื่นซึ่งฉันกำลังย้ายไปที่ Angular รหัสเก่าเป็นไปตามรูปแบบที่รหัสสนใจมากในการตรวจสอบปุ่มตัวเลือกแต่ละปุ่มเพื่อดูว่าเป็นปุ่มที่เลือกหรือไม่ โซลูชันนี้เป็นรูปแบบหนึ่งของโซลูชันตัวจัดการการคลิกซึ่งบางส่วนได้รับการกล่าวถึงแล้วใน Stack Overflow มูลค่าเพิ่มของโซลูชันนี้อาจเป็น:

  1. ทำงานร่วมกับรูปแบบของรหัสเก่าที่ฉันต้องใช้
  2. ฉันสร้างคลาสตัวช่วยเพื่อพยายามลดจำนวนคำสั่ง "if" ในตัวจัดการการคลิกและจัดการกลุ่มของปุ่มตัวเลือกใด ๆ

โซลูชันนี้เกี่ยวข้องกับ

  1. ใช้รูปแบบที่แตกต่างกันสำหรับปุ่มตัวเลือกแต่ละปุ่ม
  2. การตั้งค่าแอตทริบิวต์ "ตรวจสอบ" ด้วยรุ่นของปุ่มตัวเลือก
  3. ส่งโมเดลของปุ่มตัวเลือกที่คลิกไปยังคลาสผู้ช่วยเหลือ
  4. คลาสผู้ช่วยทำให้แน่ใจว่าโมเดลเป็นปัจจุบัน
  5. เมื่อ "ส่งเวลา" สิ่งนี้จะช่วยให้รหัสเก่าตรวจสอบสถานะของปุ่มตัวเลือกเพื่อดูว่าปุ่มใดถูกเลือกโดยการตรวจสอบโมเดล

ตัวอย่าง:

<input type="radio"
    [checked]="maleRadioButtonModel.selected"
    (click)="radioButtonGroupList.selectButton(maleRadioButtonModel)"

...

 <input type="radio"
    [checked]="femaleRadioButtonModel.selected"
    (click)="radioButtonGroupList.selectButton(femaleRadioButtonModel)"

...

เมื่อผู้ใช้คลิกปุ่มตัวเลือกเมธอด selectButton ของคลาสตัวช่วยจะถูกเรียกใช้ มันถูกส่งผ่านโมเดลสำหรับปุ่มตัวเลือกที่ถูกคลิก คลาสตัวช่วยตั้งค่าฟิลด์บูลีน "ที่เลือก" ของการส่งผ่านในโมเดลเป็นจริงและตั้งค่าฟิลด์ "ที่เลือก" ของโมเดลปุ่มตัวเลือกอื่น ๆ ทั้งหมดเป็นเท็จ

ในระหว่างการเริ่มต้นส่วนประกอบจะต้องสร้างอินสแตนซ์ของคลาสตัวช่วยพร้อมรายการรุ่นปุ่มตัวเลือกทั้งหมดในกลุ่ม ในตัวอย่าง "radioButtonGroupList" จะเป็นอินสแตนซ์ของคลาสตัวช่วยที่มีรหัส:

 import {UIButtonControlModel} from "./ui-button-control.model";


 export class UIRadioButtonGroupListModel {

  private readonly buttonList : UIButtonControlModel[];
  private readonly debugName : string;


  constructor(buttonList : UIButtonControlModel[], debugName : string) {

    this.buttonList = buttonList;
    this.debugName = debugName;

    if (this.buttonList == null) {
      throw new Error("null buttonList");
    }

    if (this.buttonList.length < 2) {
      throw new Error("buttonList has less than 2 elements")
    }
  }



  public selectButton(buttonToSelect : UIButtonControlModel) : void {

    let foundButton : boolean = false;
    for(let i = 0; i < this.buttonList.length; i++) {
      let oneButton : UIButtonControlModel = this.buttonList[i];
      if (oneButton === buttonToSelect) {
        oneButton.selected = true;
        foundButton = true;
      } else {
        oneButton.selected = false;
      }

    }

    if (! foundButton) {
      throw new Error("button not found in buttonList");
    }
  }
}

2

ตัวอย่างรายการวิทยุ Angular 8:

ลิงค์ที่มา

ใส่คำอธิบายภาพที่นี่

การตอบสนอง JSON

    [
            {
                "moduleId": 1,
                "moduleName": "Employee",
                "subModules":[
                    {
                        "subModuleId": 1,
                        "subModuleName": "Add Employee",
                        "selectedRightType": 1,
                    },{
                        "subModuleId": 2,
                        "subModuleName": "Update Employee",
                        "selectedRightType": 2,
                    },{
                        "subModuleId": 3,
                        "subModuleName": "Delete Employee",
                        "selectedRightType": 3,
                    }
                ]
            },  
            {
                "moduleId": 2,
                "moduleName": "Company",
                "subModules":[
                    {
                        "subModuleId": 4,
                        "subModuleName": "Add Company",
                        "selectedRightType": 1,
                    },{
                        "subModuleId": 5,
                        "subModuleName": "Update Company",
                        "selectedRightType": 2,
                    },{
                        "subModuleId": 6,
                        "subModuleName": "Delete Company",
                        "selectedRightType": 3,
                    }
                ]
            },  
            {
                "moduleId": 3,
                "moduleName": "Tasks",
                "subModules":[
                    {
                        "subModuleId": 7,
                        "subModuleName": "Add Task",
                        "selectedRightType": 1,
                    },{
                        "subModuleId": 8,
                        "subModuleName": "Update Task",
                        "selectedRightType": 2,
                    },{
                        "subModuleId": 9,
                        "subModuleName": "Delete Task",
                        "selectedRightType": 3,
                    }
                ]
            }
    ]

เทมเพลต HTML

        <div *ngFor="let module of modules_object">
            <div>{{module.moduleName}}</div>
            <table width="100%">

                <thead>
                    <tr>
                        <th>Submodule</th>
                        <th>
                            <input type="radio" name="{{module.moduleName}}_head_radio" [(ngModel)]="module.selHeader" (change)="selAllColumn(module)" [value]="1"> Read Only
                        </th>
                        <th>
                            <input type="radio" name="{{module.moduleName}}_head_radio" [(ngModel)]="module.selHeader" (change)="selAllColumn(module)" [value]="2"> Read Write
                        </th>
                        <th>
                            <input type="radio" name="{{module.moduleName}}_head_radio" [(ngModel)]="module.selHeader" (change)="selAllColumn(module)" [value]="3"> No Access
                        </th>
                    </tr>
                </thead>

                <tbody>
                    <tr *ngFor="let sm of module.subModules">
                        <td>{{sm.subModuleName}}</td>
                        <td>
                            <input type="radio" [checked]="sm.selectedRightType == '1'" [(ngModel)]="sm.selectedRightType" name="{{sm.subModuleId}}_radio" [value]="1"> 
                        </td>
                        <td class="cl-left">
                            <input type="radio" [checked]="sm.selectedRightType == '2'" [(ngModel)]="sm.selectedRightType" name="{{sm.subModuleId}}_radio" [value]="2"> 
                        </td>
                        <td class="cl-left">
                            <input type="radio" [checked]="sm.selectedRightType == '3'" [(ngModel)]="sm.selectedRightType" name="{{sm.subModuleId}}_radio" [value]="3"> 
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

1

วิธีแก้ปัญหาและวิธีแก้ปัญหาที่ง่ายที่สุด:

<input name="toRent" type="radio" (click)="setToRentControl(false)">
<input name="toRent" type="radio" (click)="setToRentControl(true)">

setToRentControl(value){
    this.vm.toRent.updateValue(value);
    alert(value); //true/false
}

2
คุณจะตั้งค่าปุ่มตัวเลือกเป็นค่าเริ่มต้นตั้งแต่ต้นได้อย่างไร?
EricC

นอกจากนี้ยังมีสถานการณ์ที่ผู้ใช้เปลี่ยนตัวเลือกบ่อยๆทุกครั้งจะมีฟังก์ชั่นสำหรับการตรวจสอบทุกครั้ง
blackHawk

1

ฉันได้สร้างเวอร์ชันโดยใช้เพียงเหตุการณ์คลิกบนองค์ประกอบที่โหลดและส่งค่าของสิ่งที่เลือกไปยังฟังก์ชัน "getSelection" และอัปเดตโมเดล

ในเทมเพลตของคุณ:

<ul>
     <li *ngFor="let p of price"><input type="radio" name="price"      (click)="getValue(price.value)" value="{{p}}" #price> {{p}} 
     </li>
</ul>

ชั้นเรียนของคุณ:

export class App {

  price:string;

  price = ["1000", "2000", "3000"];

  constructor() {   }

  model = new SomeData(this.price);

  getValue(price){
    this.model.price = price;
  }
}

ดูตัวอย่าง: https://plnkr.co/edit/2Muje8yvWZVL9OXqG0pW?p=info


1

คำตอบนี้อาจไม่ดีที่สุดเท่าที่จะทำได้ทั้งนี้ขึ้นอยู่กับกรณีการใช้งานของคุณมันใช้ได้ผล แทนที่จะใช้ปุ่มวิทยุสำหรับการเลือกชายและหญิงใช้<select> </select>งานได้อย่างสมบูรณ์แบบทั้งเพื่อการบันทึกและการแก้ไข

<select formControlName="gender" name="gender" class="">
  <option value="M">Male</option>
  <option value="F">Female</option>
</select>

ดังกล่าวข้างต้นควรจะทำอย่างไรดีเพียงสำหรับการแก้ไขโดยใช้ FormGroup patchValueกับ สำหรับการสร้างคุณสามารถใช้[(ngModel)]แทนไฟล์formControlName. ยังใช้งานได้

งานประปาที่เกี่ยวข้องกับปุ่มตัวเลือกหนึ่งฉันเลือกที่จะเลือกใช้แทน ด้วยสายตาและ UX ดูเหมือนจะไม่ดีที่สุด แต่จากมุมมองของผู้พัฒนามันง่ายกว่ามาก


1

บนปุ่มวิทยุเปลี่ยนรับค่าของปุ่มตามลำดับด้วยบรรทัดเหล่านี้

<label class="radio-inline">
<input class="form-check-input" type="radio" [(ngModel)]="dog" name="cat"  checked (change)="onItemChange($event)" value="Dog" />Dog</label>
<label class="radio-inline">
<input class="form-check-input" type="radio" [(ngModel)]="cat" name="cat"   (change)="onItemChange($event)" value="Cat"  />Cat</label>

https://stackblitz.com/edit/angular-jpo2dm?embed=1&file=src/app/app.component.html


0

นี่คือรหัสบางส่วนที่ฉันใช้ซึ่งใช้ได้กับ Angular 7

(หมายเหตุ: ในอดีตบางครั้งฉันใช้ข้อมูลจากคำตอบของ Anthony Brenelièreซึ่งฉันรู้สึกขอบคุณ แต่อย่างน้อยสำหรับ Angular 7 ส่วนนี้:

 [checked]="model.options==2"

ฉันพบว่าไม่จำเป็น)

ทางออกของฉันที่นี่มีข้อดีสามประการ:

  1. สอดคล้องกับโซลูชันที่แนะนำโดยทั่วไป ดังนั้นจึงเป็นเรื่องดีสำหรับโครงการใหม่
  2. ยังอนุญาตให้รหัสปุ่มตัวเลือกคล้ายกับรหัส Flex / ActionScript นี่เป็นสิ่งสำคัญส่วนตัวเพราะฉันกำลังแปลโค้ด Flex เป็น Angular เช่นเดียวกับรหัส Flex / ActionScript ช่วยให้รหัสทำงานบนวัตถุปุ่มตัวเลือกเพื่อตรวจสอบหรือยกเลิกการเลือกหรือดูว่ามีการตรวจสอบปุ่มตัวเลือกหรือไม่
  3. ซึ่งแตกต่างจากโซลูชันส่วนใหญ่ที่คุณจะเห็นมันเป็นแบบออบเจ็กต์มาก ข้อดีอย่างหนึ่งคือการจัดระเบียบ: จัดกลุ่มเขตข้อมูลการผูกข้อมูลของปุ่มตัวเลือกเข้าด้วยกันเช่นเลือกเปิดใช้งานมองเห็นได้และอื่น ๆ

ตัวอย่าง HTML:

       <input type="radio" id="byAllRadioButton"
                 name="findByRadioButtonGroup"
                 [(ngModel)]="findByRadioButtonGroup.dataBindingValue"
                 [value]="byAllRadioButton.MY_DATA_BINDING_VALUE">         

      <input type="radio" id="byNameRadioButton"
                 name="findByRadioButtonGroup" 
                 [(ngModel)]="findByRadioButtonGroup.dataBindingValue"
                 [value]="byNameRadioButton.MY_DATA_BINDING_VALUE">

ตัวอย่าง TypeScript:

 findByRadioButtonGroup : UIRadioButtonGroupModel
    = new UIRadioButtonGroupModel("findByRadioButtonGroup",
                                  "byAllRadioButton_value",
                                  (groupValue : any) => this.handleCriteriaRadioButtonChange(groupValue)
                                  );

  byAllRadioButton : UIRadioButtonControlModel
    = new UIRadioButtonControlModel("byAllRadioButton",
    "byAllRadioButton_value",
    this.findByRadioButtonGroup) ;

  byNameRadioButton : UIRadioButtonControlModel
    = new UIRadioButtonControlModel("byNameRadioButton",
    "byNameRadioButton_value",
    this.findByRadioButtonGroup) ;



  private handleCriteriaRadioButtonChange = (groupValue : any) : void => {

    if ( this.byAllRadioButton.selected ) {

      // Do something

    } else if ( this.byNameRadioButton.selected ) {

      // Do something

    } else {
      throw new Error("No expected radio button selected");
    }
  };

ใช้สองคลาส:

คลาสกลุ่มปุ่มตัวเลือก:

export class UIRadioButtonGroupModel {


  private _dataBindingValue : any;


  constructor(private readonly debugName : string,
              private readonly initialDataBindingValue : any = null,   // Can be null or unspecified
              private readonly notifyOfChangeHandler : Function = null       // Can be null or unspecified
  ) {

    this._dataBindingValue = initialDataBindingValue;
  }


  public get dataBindingValue() : any {

    return this._dataBindingValue;
  }


  public set dataBindingValue(val : any) {

    this._dataBindingValue = val;
    if (this.notifyOfChangeHandler != null) {
      MyAngularUtils.callLater(this.notifyOfChangeHandler, this._dataBindingValue);
    }
  }



  public unselectRadioButton(valueOfOneRadioButton : any) {

    //
    // Warning: This method probably never or almost never should be needed.
    // Setting the selected radio button to unselected probably should be avoided, since
    // the result will be that no radio button will be selected.  That is
    // typically not how radio buttons work.  But we allow it here.
    // Be careful in its use.
    //

    if (valueOfOneRadioButton == this._dataBindingValue) {
      console.warn("Setting radio button group value to null");
      this.dataBindingValue = null;
    }
  }

};

คลาสปุ่มตัวเลือก

export class UIRadioButtonControlModel {


  public enabled : boolean = true;
  public visible : boolean = true;


  constructor(public readonly debugName : string,
              public readonly MY_DATA_BINDING_VALUE : any,
              private readonly group : UIRadioButtonGroupModel,
              ) {

  }


  public get selected() : boolean {

    return (this.group.dataBindingValue == this.MY_DATA_BINDING_VALUE);
  }


  public set selected(doSelectMe : boolean) {

    if (doSelectMe) {
      this.group.dataBindingValue = this.MY_DATA_BINDING_VALUE;
    } else {
      this.group.unselectRadioButton(this.MY_DATA_BINDING_VALUE);
    }
  }

}

-1

นี่อาจไม่ใช่วิธีแก้ปัญหาที่ถูกต้อง แต่ก็เป็นทางเลือกที่หวังว่ามันจะช่วยใครบางคนได้

จนถึงตอนนี้ฉันได้รับค่าของ radioButtons โดยใช้วิธี (คลิก) ดังต่อไปนี้:

<input type="radio" name="options" #male (click)="onChange(male.value)">Male
<input type="radio" name="options" #female (click)="onChange(female.value)">Female

และในไฟล์. ts ฉันได้ตั้งค่าของตัวแปรที่กำหนดไว้ล่วงหน้าเป็นค่า getter ของonChangeฟังก์ชัน

แต่หลังจากการค้นหาผมพบว่าวิธีการที่ดีฉัน have't พยายามยัง แต่ดูเหมือนว่าคนนี้เป็นสิ่งที่ดีโดยใช้[(ng-model)]การเชื่อมโยงที่นี่เพื่อ GitHub ที่นี่ นี่ใช้RadioControlValueAccessorสำหรับวิทยุและช่องทำเครื่องหมายด้วย นี่คือการทำงาน # plnkr # สำหรับวิธีการนี้ ที่นี่

โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.