RollADie
RollADie

Reputation: 179

NgModel isn't reflecting the selected value from a dropdown whose values get populated based on another dropdown

When the component is loaded, I want mainTask and mainJob to be reflected as a selection in the dropdown, mainTask is reflected as expected but mainJob isnt updated in the UI. However, if I manually select a value in UI from the taskList, mainJob is updated accordingly. Looks like mainJob isn't getting reflected because the jobList dropdown is triggered by the selection of mainTask. How can I correct my code?

html file

<mat-form-field>
              <mat-select [(ngModel)]="mainTask">
                <mat-option *ngFor="let task of taskList"
                            [value]="task"
                            (click)="getJobs()">
                  {{task}}
                </mat-option>
              </mat-select>
            </mat-form-field>

    <mat-form-field>
              <mat-select [(ngModel)]="mainJob">
                <mat-option *ngFor="let job of jobList"
                            [value]="job">
                  {{job}}
                </mat-option>
              </mat-select>
            </mat-form-field>

ts file

ngOnInit(): void {
    this.taskList = ['task1','task2','task3'];
    this.jobList = ['job1','job2','job3'];
    this.mainTask = 'task2';
    this.mainJob = 'job2';
}
getJobs():void {
    if(mainTask){
       const jobIndex = this.taskList.indexOf(this.mainTask);
       this.jobList.splice(0, jobIndex);
    }
}

Upvotes: 0

Views: 66

Answers (1)

Hrishikesh Kale
Hrishikesh Kale

Reputation: 6558

yes, the mainJob is selected only when getjobs() function is called,

you can assign a value to mainJob in a component like

mainJob:string = 'job2';

and not in ngOnIt. check this plunker here

Upvotes: 1

Related Questions