简体   繁体   中英

How can I use radio button for choosing gender in my ionic 3 angular app?

I am new to angular and ionic 3 . Now only I'm learning it.

Currently, I'm using the angular forms for getting the employee details and saving it in the database table.

It contains the following fields firstname , lastname , gender , DOB , Departmnet etc.

For gender currently, I'm using modal drop-down box which contains two values(Male and Female) & selecting it.

I need to use radio-button for choosing it instead of the modal drop-down.

How can I implement it?

Please, guide me. I've only a little knowledge in HTML and CSS too. Please currently need your help guys. An example link or tutorial is highly appreciated. I have already tried to implement the radio-buttons using <ion-list> , but it ends up with alignment problems.

I have mentioned here whatever I've tried so far.

employee-details.html:

<ion-item no-lines>
<ion-icon class="iconstyle" name="md-contacts" item-start></ion-icon>
<ion-label floating color="primary">Gender</ion-label>
<ion-select class="mydate" formControlName="gender" [(ngModel)]="vm.gender" class="textcolor" value="gender">
<ion-option *ngFor="let item of genderlist" value="{{item.key}}">{{item.value}}</ion-option>
</ion-select>
</ion-item>
<div class="error-message-emp" *ngIf="formemp.controls.gender.errors && (formemp.controls.gender.dirty || formemp.controls.gender.touched)">
<span *ngIf="formemp.controls.gender.errors?.required">Gender is required</span>
</div>

Here i have specified how I have taken the key values for gender in the array

employee-details.ts:

import { Component } from '@angular/core';
import {IonicPage, NavController, NavParams, Platform } from 'ionic-angular';
import {EmployeeService} from '../../services/employee.service';
import {compareValidator} from '../../shared/directives/comparevalidator';
import { MessageService } from '../../services/message.service';
import { Keyboard } from '@ionic-native/keyboard';

import { BroadCastService } from '../../services/broadcast.service';
import { isNullOrUndefined } from 'util';
import { Employee } from '../../models/employee';
import { FormGroup, FormControl, Validators, AbstractControl} from '@angular/forms';

/**
 * Generated class for the EmployeeDetailsPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-employee-details',
  templateUrl: 'employee-details.html',
  providers :[EmployeeService]
})
export class EmployeeDetailsPage {
  formemp: FormGroup;
  value: any;
  setdeptlist = [];
  emailpattern: string = "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[a-z]{2,3}$";
  vm: Employee;



  constructor(public navCtrl: NavController, public navParams: NavParams, private employeeservice: EmployeeService, private message: MessageService,private platform: Platform,  public keyboard: Keyboard, public broadCastService: BroadCastService,) 
  {
    employeeservice.getdepartment().subscribe(res =>{
      console.log(res);
      if(!isNullOrUndefined(res)) {
        this.setdeptlist = res;

      }
    })
    this.vm = new Employee();

  }

    ngOnInit() {
      this.initializeValidators();
    }
    initializeValidators(){
      this.formemp = new FormGroup({
        firstname : new FormControl ('', [Validators.required]),
        lastname : new FormControl ('', [Validators.required]),
        dob: new FormControl('', Validators.required),
        email: new FormControl('', {
          validators: [Validators.required, Validators.pattern(this.emailpattern)]
        }),
        gender: new FormControl('', Validators.required),
        dept: new FormControl('', Validators.required),
        others: new FormControl(null)

})
}
    resetForm(formGroup: FormGroup) {
      let control: AbstractControl = null;
      formGroup.reset();
      formGroup.markAsUntouched();
      Object.keys(formGroup.controls).forEach((name) => {
        control = formGroup.controls[name];
        control.setErrors(null);
      });
      this.initializeValidators();
    }
    submit(){
      if(this.formemp.valid){
        this.employeeservice.saveemployee(this.vm).subscribe(res=>{
          console.log(res);
          this.message.alert("Details has been added Successfully");
          this.resetForm(this.formemp);
        }, err => {
          this.message.alert(JSON.stringify(err.error));
      } )
      }
      else {
        this.validateFormControl(this.formemp);
      }
    }

departmentChange(event){
      debugger;
var check = event;
 var che =this.vm.dept;
 const others = this.formemp.get('others');
 if(this.vm.dept == "6" ){
   others.setValidators(Validators.required);

 }
 else{
   others.clearValidators();
 }
 others.updateValueAndValidity();

    }

  ionViewDidLoad() {
    console.log('ionViewDidLoad EmployeeDetailsPage');
  }

  moveFocus(event, nextElement, isLastControl) {
    if (event.key === 'Enter') {
      if (isLastControl && isLastControl === false)
          nextElement.setFocus();
      else if (isLastControl && isLastControl === true)
          this.submit();
  }
  }
  validateFormControl(formGroup: FormGroup) {
    Object.keys(formGroup.controls).forEach(field => {
      const control = formGroup.get(field);
      if (control instanceof FormControl) {
        control.markAsTouched({ onlySelf: true });
      } else if (control instanceof FormGroup) {
        this.validateFormControl(control);
      }
    });
  }
  genderlist = [
    { key: 1, value: "Male" },
    { key: 2, value: "Female" }
  ];
}

Here I have mentioned my service class for getting the gender value from API

employee-service.ts:

import { Injectable } from "@angular/core";
import { DataService } from "./data.service";


@Injectable()
export class EmployeeService {
    constructor(private dataservice: DataService) {

    }
    getgender(){
        return this.dataservice.getData('/api/lookup/getgender',true);
    }
}

Kindly help me guys. A million thanks in advance.

for your <ion-select> code it should look like this:

 <ion-item no-lines> <ion-icon class="iconstyle" name="md-contacts" item-start></ion-icon> <ion-label floating color="primary">Gender</ion-label> <ion-select class="mydate" formControlName="gender" [(ngModel)]="gender" class="textcolor" value="gender"> <ion-option *ngFor="let item of genderlist" value="{{item.key}}">{{item.value}}</ion-option> </ion-select> </ion-item> 

As for your form controls on the bottom in your div and span statements, You may need to update your question with more of your employee-details.ts code. I commented out those two statements and the select worked just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM