Search code examples
angularselecteditemprimeng-dropdowns

Angular PrimeNG dropdown : set value selected on load


I have PrimeNG dropdown in my app on dashboard page. Now I want that when dashboard page get load it should have value selected. it should select current financial year. But not working right now. Code is given below

ts file code :

    export class WelcomeComponent implements OnInit, OnDestroy {
  financialYears: any;
  selectedYear = null;

   isReady: boolean | undefined;
  constructor() {
  }

  ngOnInit() {

    this.financialYears = [
      { "name": '2022-23', "code": '2022-2023' },
      { "name": '2023-24', "code": '2023-2024' },
      { "name": '2024-25', "code": '2024-2025' },
      { "name": '2025-26', "code": '2025-2026' },
      { "name": '2026-27', "code": '2026-2027' },
      { "name": '2027-28', "code": '2027-2028' },
      { "name": '2028-29', "code": '2028-2029' },
      { "name": '2029-30', "code": '2029-2030' }
    ];

    this.load();
  }

  load() {
    let currentDate: Date = new Date();

    let fyYear = currentDate.getMonth() >= 4 ? (currentDate.getFullYear() + "-" + (currentDate.getFullYear() + 1)) : ((currentDate.getFullYear() - 1) + "-" + currentDate.getFullYear())
    debugger;
    this.selectedYear = this.financialYears.find((o: { code: string; }) => o.code == fyYear);
    this.isReady = true;
    //this.selectedYear = slY;
  }
}

html file code

<p-dropdown [options]="financialYears" [(ngModel)]="selectedYear"  *ngIf="isReady" optionLabel="name" optionValue="code" (onChange)="onChange($event)"></p-dropdown>

But this is not working. Any other way to set selected?


Solution

  • As you have optionValue="code" but you are patching the whole object that is why it is not getting patched.

    Please try like this:

    load() {
        let currentDate: Date = new Date();
    
        let fyYear = currentDate.getMonth() >= 4 ? (currentDate.getFullYear() + "-" + (currentDate.getFullYear() + 1)) : ((currentDate.getFullYear() - 1) + "-" + currentDate.getFullYear())
        debugger;
        this.selectedYear = this.financialYears.find((o: { code: string; }) => o.code == fyYear).code;
        this.isReady = true;
        //this.selectedYear = slY;
      }