默认选中Angular 4默认单选按钮

时间:2017-05-04 10:51:43

标签: angular object radio-button angular-ng-if

我试图根据我从对象获得的值标记为默认的单选按钮,它可以是True或False。根据选项,我可以做什么来标记为默认的单选按钮?

<label>This rule is true if:</label>
<label class="form-check-inline">
    <input class="form-check-input" type="radio" name="mode" value="true" 
        [(ngModel)]="rule.mode"> all of the following conditions are true
</label>
<label class="form-check-inline">
    <input class="form-check-input" type="radio" name="mode" value="false"
        [(ngModel)]="rule.mode"> at least one of the following conditions is true
</label>

我在rule.mode中设置了真或假。

5 个答案:

答案 0 :(得分:50)

您可以使用procedure TForm1.Button5Click(Sender: TObject); var MS : TMemoryStream; begin // Requires TFDStanStorageBinLink on form/datamodule MS := TMemoryStream.Create; try FDMemTable1.SaveToStream(MS); FDMemTable1.Close; // sometime later MS.Position := 0; FDMemTable1.LoadFromStream(MS); finally MS.Free; end; end; ,但是您需要将[(ngModel)]更新为value,否则该值将作为字符串进行评估。它看起来像这样:

[value]

如果<label>This rule is true if:</label> <label class="form-check-inline"> <input class="form-check-input" type="radio" name="mode" [value]="true" [(ngModel)]="rule.mode"> </label> <label class="form-check-inline"> <input class="form-check-input" type="radio" name="mode" [value]="false" [(ngModel)]="rule.mode"> </label> 为真,则选择该无线电。如果它是假的,那么另一个。

差异真正归结为rule.modevalue确实计算字符串&#39; true&#39;,而value="true"计算为布尔值true。

答案 1 :(得分:4)

我们可以通过以下方式使用 [(ngModel)] 并具有值选择变量 radioSelected

Example tutorial

Demo Link

app.component.html

  <div class="text-center mt-5">
  <h4>Selected value is {{radioSel.name}}</h4>

  <div>
    <ul class="list-group">
          <li class="list-group-item"  *ngFor="let item of itemsList">
            <input type="radio" [(ngModel)]="radioSelected" name="list_name" value="{{item.value}}" (change)="onItemChange(item)"/> 
            {{item.name}}

          </li>
    </ul>
  </div>


  <h5>{{radioSelectedString}}</h5>

  </div>

app.component.ts

  import {Item} from '../app/item';
  import {ITEMS} from '../app/mock-data';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
  })
  export class AppComponent {
    title = 'app';
    radioSel:any;
    radioSelected:string;
    radioSelectedString:string;
    itemsList: Item[] = ITEMS;


      constructor() {
        this.itemsList = ITEMS;
        //Selecting Default Radio item here
        this.radioSelected = "item_3";
        this.getSelecteditem();
      }

      // Get row item from array  
      getSelecteditem(){
        this.radioSel = ITEMS.find(Item => Item.value === this.radioSelected);
        this.radioSelectedString = JSON.stringify(this.radioSel);
      }
      // Radio Change Event
      onItemChange(item){
        this.getSelecteditem();
      }

  }

要列出的示例数据

        export const ITEMS: Item[] = [
            {
                name:'Item 1',
                value:'item_1'
            },
            {
                name:'Item 2',
                value:'item_2'
            },
            {
                name:'Item 3',
                value:'item_3'
            },
            {
                name:'Item 4',
                value:'item_4'
                },
                {
                    name:'Item 5',
                    value:'item_5'
                }
        ];

答案 2 :(得分:0)

<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
   <div>
      <input id="male" type="radio" value="male" name="gender" formControlName="gender">
      <label class="custom-control-label" for="male">Male</label>
   </div>
   <div>
      <input id="female" type="radio" value="female" name="gender" formControlName="gender">
      <label class="custom-control-label" for="female">Female</label>
   </div>
   <!-- Showing error method -->
   <div *ngIf="isSubmitted && myForm.errors?.required">
      <p>Please select either value</p>
   </div>

   <button type="submit">Submit</button>
</form>

要设置在Angular中选择的单选按钮,我们将在from控件数组中传递单选按钮的值,如下所示。它将在Angular的反应式表单中设置单选按钮的选定值。

registrationForm = this.fb.group({
    gender: ['male']
 })

请参阅:Radio in angular

答案 3 :(得分:0)

出现以下错误

It happens:  Error: 
      ngModel cannot be used to register form controls with a parent formGroup directive.  Try using
      formGroup's partner directive "formControlName" instead.  Example:

答案 4 :(得分:0)

如果您使用的是反应式形式,那么您可以使用以下方式。 考虑以下示例。

在 component.html 中

 `<p class="mr-3"> Require Shipping: 

          <input type="radio" class="ml-2" value="true" name="requiresShipping" 
           id="requiresShipping" formControlName="requiresShipping">

                   &nbsp;  Yes  &nbsp;

          <input type="radio" class="ml-2" value="false" name="requiresShipping" 
          id="requiresShipping" formControlName="requiresShipping">

                   &nbsp;  No   &nbsp;
 </p>`

在 component.ts 中

`
 export class ClassName implements OnInit {
      public yourForm: FormGroup
      
      constructor(
            private fromBuilder: FormBuilder
      ) {
            this.yourForm= this.fromBuilder.group({
                  requiresShipping: this.fromBuilder.control('true'),
            })
        }
 }

`

现在您将获得默认选择的单选按钮。

enter image description here