Sampath
Sampath

Reputation: 65870

Cannot set default selection on <ion-select> on Reactive form

I need to load <ion-select> dynamically in a reactive form.It is working fine.Now I need to set default selection.I have used selected attribute for that.But it is not working.Can you tell me why?

Here is the Plunker

app/home.page.html

<form [formGroup]="detailInformationForm" (submit)="goToSponsor(detailInformationForm)" novalidate>
    <ion-item>
      <ion-label>Donation</ion-label>
      <ion-select formControlName="donationdate">
        <ion-option *ngFor="let date of donationDates" value="{{date.donationdate}}" [selected]="date.isChecked">
          {{date.donationdate}}</ion-option>
      </ion-select>
    </ion-item>
       <button ion-button block type="submit" [disabled]="!detailInformationForm.valid">Next</button>
  </form>

app/home.page.ts

export class HomePage {
  donationDates:any=[];
  detailInformationForm: FormGroup;

  constructor(public navController: NavController,public formBuilder: FormBuilder) { 
      this.donationDates = [
       {
          id: null,
          donationid: "2",
          donationdate: "2017-03-12",
          datedescription: "Vad Bij",
          isChecked:true
      },
      {
        id: null,
       donationid: "2",
       donationdate: "2017-03-19",
       datedescription: "Sud satam",
       isChecked:false
     }]

     this.detailInformationForm = formBuilder.group({
      donationdate: ['', Validators.required]
    });
  }

}

Update:

 this.getDonation().then((val) => {//get Donation
      this.donation = val;
      if (this.donation.sponsordata == 1) {
        this.detailInformationForm.controls['attendees'].validator = Validators.required;
      }

      let donationDates = this.donation.donationdates;
      let dates = [];
      _.forEach(donationDates, function (value, key) {
        value.isChecked = false;
        if (key == 0) {
          value.isChecked = true;
        }
        dates.push(value);
      });
      this.donationDates = dates;

    });

Upvotes: 4

Views: 1604

Answers (1)

cartant
cartant

Reputation: 58400

The control in the reactive form will be managing the selected item.

Instead of specifying the selected attribute, just specify the value for the donationdate control that is to be selected:

this.donationDates = [
  {
    id: null,
    donationid: "2",
    donationdate: "2017-03-12",
    datedescription: "Vad Bij",
    isChecked: true
  },
  {
    id: null,
    donationid: "2",
    donationdate: "2017-03-19",
    datedescription: "Sud satam",
    isChecked: false
  }
]
const checked = this.donationDates.find(donationDate => donationDate.isChecked);

this.detailInformationForm = formBuilder.group({
  donationdate:
    [
      checked ? checked.donationdate : null,
      Validators.required
    ]
});

Upvotes: 1

Related Questions