如何在编辑表单中设置单选按钮选择的值

时间:2018-08-05 06:25:05

标签: angular typescript radio-button angular6

我正在使用ReactiveFormModule创建编辑表单。我想在editform中显示数据,例如在文本框,下拉列表,单选框和复选框中。我可以使用setValue方法成功设置文本框和下拉列表的值。但我无法使用相同的值来设置广播组的值。

打字稿

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, AbstractControl, ValidationErrors, FormControlName } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Observable, EMPTY, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.css'],
})
export class AddComponent implements OnInit {
  stateList : any;
  cityList: any;
  genderList: any;
  hobbyList: any;
  name: FormControl;
  age: FormControl;
  state : FormControl;
  city: FormControl;
  myform: FormGroup;
  gender: FormControl;
  hobby: FormControl;
  file: FormControl;
  email: FormControl;
  confirmEmail: FormControl;

  submitted = false;

  constructor(private http: HttpClient) {
    this.name = new FormControl("", [Validators.required, Validators.email, Validators.minLength(6), Validators.pattern("")]);
    this.age = new FormControl("27", [checkageValidator]);
    this.state = new FormControl("");
    this.city = new FormControl("", Validators.required);
    this.gender = new FormControl("");
    this.hobby = new FormControl("");
    this.file = new FormControl("");
    this.email = new FormControl("");
    this.confirmEmail = new FormControl("", [compareEmail]);

    this.myform = new FormGroup({
      name: this.name,
      age: this.age,
      state : this.state,
      city: this.city,
      gender: this.gender,
      hobby: this.hobby,
      file: this.file,
      email: this.email,
      Cemail: this.confirmEmail
    });

    this.stateList = [{value : 1, text: "Gujarat"}, {value : 2, text : "Maharastra"}];
    this.cityList = [{ value: 1, text: "Ahmedabad", stateid: 1 }, { value: 2, text: "Rajkot", stateid: 1 }, { value: 3, text: "Gandhinagar", stateid: 2 }];
    this.genderList = [{ value: 1, text: "Male", selected: "checked" }, { value: 2, text: "Female", selected: "" }];
    this.hobbyList = [{ value: 1, text: "Games", checked:false }, { value: 2, text: "Tracking", checked:false }, { value: 3, text: "Swimming", checked:false }];
  }

  ngOnInit() {
    this.myform.controls["name"].setValue("Hardik");
    this.myform.controls["state"].setValue("1");
    this.genderList.find(i=>i.value == 2).selected == "checked";
  }
}

HTML

<form novalidate [formGroup]="myform" (ngSubmit)="SubmitData(myform)">
    <div class="row">
        <div class="col-lg-12">
            <div class="col-xs-4">
                Name:
            </div>
            <div class="col-xs-8">
                <input type="text" id="txtName" formControlName="name" class="form-control" [ngClass]="{'error' : myform.controls.name.errors && submitted}">
                <div *ngIf="submitted && myform.controls.name.errors">
                    <span class="alert-danger form-control" *ngIf="myform.controls.name.errors?.required">Name is required field</span>
                </div>
            </div>
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-lg-12">
            <div class="col-xs-4">
                Email:
            </div>
            <div class="col-xs-8">
                <input type="text" id="txtEmail" formControlName="email" class="form-control" [ngClass]="{'error' : myform.controls.email.errors && submitted}">
                <div *ngIf="submitted && myform.controls.email.errors">
                    <span class="alert-danger form-control" *ngIf="myform.controls.email.errors?.required">Email is required field</span>
                </div>
            </div>
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-lg-12">
            <div class="col-xs-4">
                CEmail:
            </div>
            <div class="col-xs-8">
                <input type="text" id="txtCEmail" formControlName="Cemail" class="form-control" [ngClass]="{'error' : myform.controls.Cemail.errors && submitted}">
                <div *ngIf="submitted && myform.controls.Cemail.errors">
                    <span class="alert-danger form-control" *ngIf="myform.controls.Cemail.errors?.emailMatch">Email not match</span>
                </div>
            </div>
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-lg-12">
            <div class="col-xs-4">
                Age:
            </div>
            <div class="col-xs-8">
                <input type="text" id="txtAge" formControlName="age" class="form-control" [ngClass]="{'error' : myform.controls.name.errors && submitted}">
                <div *ngIf="submitted && myform.controls.age.errors">
                    <span class="alert-danger form-control" *ngIf="myform.controls.age.errors?.required">Age is required field</span>
                    <span class="alert-danger form-control" *ngIf="myform.controls.age.errors?.validAge">Age must greater than 18</span>
                </div>
            </div>
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-lg-12">
            <div class="col-xs-4">
                State:
            </div>
            <div class="col-xs-8">
                <select class="form-control" formControlName="state" (change)="getCities($event.target.value)">
                    <option value="">Select State</option>        
                    <option *ngFor="let s of stateList" value="{{s.value}}">{{s.text}}</option>
                </select>
                <div *ngIf="submitted && myform.controls.state.errors">
                    <span class="alert-danger form-control" *ngIf="myform.controls.state.errors?.required">State is Required</span>
                </div>
            </div>
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-lg-12">
            <div class="col-xs-4">
                City:
            </div>
            <div class="col-xs-8">
                <select class="form-control" formControlName="city">
                    <option value="">Select City</option>
                    <option *ngFor="let c of cityList" value="{{c.value}}">{{c.text}}</option>
                </select>
                <div *ngIf="submitted && myform.controls.city.errors">
                    <span class="alert-danger form-control" *ngIf="myform.controls.city.errors?.required">City is Required</span>
                </div>
            </div>
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-lg-12">
            <div class="col-xs-4">
                Radio:
            </div>
            <div class="col-xs-8">
                <label class="radio-inline" *ngFor="let g of genderList">
                    <input type="radio" [value]="g.value" name="gender" formControlName="gender" [checked]="g.selected">{{g.text}}
                </label>
            </div>
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-lg-12">
            <div class="col-xs-4">
                CheckBox:
            </div>
            <div class="col-xs-8">
                <label class="checkbox-inline" *ngFor="let g of hobbyList">
                    <input type="checkbox" value="{{g.value}}" name="hobbie" formControlName="hobby" [(ngModel)]="g.checked">{{g.text}}
                </label>
            </div>
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-lg-12">
            <div class="col-xs-4">
                File:
            </div>
            <div class="col-xs-8">
                <img *ngIf="fileURL != null" [src]="fileURL" style="width: 250px; height: 250;">
                <input type="file" name="file" formControlName="file" accept="image/*" (change)="uploadImage($event.target.files)">
            </div>
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-lg-12">
            <div class="col-xs-4">
            </div>
            <div class="col-xs-8">
                <button type="submit" class="btn btn-default pull-left">Submit</button>
            </div>
        </div>
    </div>
</form>

如您所见,setValue不适用于我的RadioButton。所以我相应地设置了我的JsonData selected属性,根据最佳实践,这实际上是错误的。是吗?

什么是最好的方法?

1 个答案:

答案 0 :(得分:1)

对于单选输入的“ checked”属性,可以检查表单的当前值是否等于单选输入的值。

 <label class="radio-inline" *ngFor="let g of genderList">
                    <input type="radio" [value]="g.value" name="gender" formControlName="gender" 

[checked]="myform.get('gender').value == g.value">{{g.text}}
                    </label>

然后在组件中,可以为表单分配所需的值。

this.myform.controls["gender"].setValue(2);

这里是StackBlitz Demo