Search code examples
angularionic-frameworkionic3ionic4

ionic 4: i got errror during using (ionChange) Select-Option to display students who selected specific subject


i am trying to show students who selected specific subject after selecting subject in select-option , when i use (ionChange)=viewStudents(subject.subid,subject.name)i got error this error: Cannot read property 'subid' of undefined at Object.eval [as handleEvent] (MarksViewPage.html:127) actually when i use viewStudents(subject.subid,subject.name) on (click) in other method its work.

please help me to solve this error

html:

    <ion-item>
      <ion-select [(ngModel)]="selected" (ionChange)="viewStudents(subject.subid,subject.name)">
     <ion-select-option *ngFor="let subject of choosedSubjects_viewMarks;let i=index" 
     [value]="subject.subid">{{subject.name}}</ion-select-option> 
    </ion-select>
    </ion-item>

.ts file:

    async viewStudents(sub_id,sub_name) {
         this.SujectID = sub_id;
         this.title = sub_name;
         this.enable_subjects = false; 
         **this.enable_students = true;**
         this.searchlistResult = false;
         this.ionViewDidEnter() ;
            }

when i disable other lists this list will display:

  async viewMarks(studentid,input) {

        console.log(studentid, this.teach_id, this.SujectID, input);

        return new Promise(resolve => {
          let body = {
          aksi: 'add_marks',
          sid:   studentid,
          tid:   this.teach_id,
          subID: this.SujectID,
          marks: input
        }
        this.accessProvds.postData(body,'proses_api.php').subscribe((res: any) => {
          if (res.success == true) {
            this.presentToast('Added successfuly!');
            this.ionViewDidEnter();

          } else {
            this.presentToast(res.msg);
          }
        });


      });

Solution

  • Your subject is defined as an iterator of ngFor directive. However, your ionChange is defined outside. Thus it does not know what is subject.

    In order to make your code working your template should look as follows:

    <ion-item>
         <ion-select [(ngModel)]="selected"
                     (ionChange)="viewStudents(selected.subid,selected.name)">
         <ion-select-option *ngFor="let subject of choosedSubjects_viewMarks; let i=index" 
         [value]="subject">{{subject.name}}</ion-select-option> 
        </ion-select>
    </ion-item>
    

    Please note two important points:

    1. I'm passing the whole subject object as option value
    2. I'm passing to viewStudents the selected object as long as it is defined in ngModel