vamsi
vamsi

Reputation: 1586

Alternative method for setTimeout in Angular

I am currently working on Angular project which is new to me. I have a requirement where I need to set a kendo dropdown value to it's default state after selecting an option.

.ts file

griddefaultItem = { text: 'Grid Actions', value: '' };
gridActions = [
{ text: 'Customize Grid Display', value: 'CGD' },
{ text: 'Download Grid To Excel', value: 'DGE' }
];

gridDisplay(obj: OptionalList) {
setTimeout(() => {
  this.gridselectedValue = this.griddefaultItem[0];
}, 10);
if (obj.value === 'CGD') {
  this.gridActionValue = true;
  this.getPopupDef();
  this.getPopupDetails();
}
}

html

<kendo-dropdownlist data-test-id="GA_B" [data]="gridActions" [defaultItem]="griddefaultItem" [textField]="'text'"
  [valueField]="'value'" (selectionChange)="gridDisplay($event)" [(value)]="gridselectedValue" class="dropdown_list"
  [popupSettings]="{ width: 170 }">
</kendo-dropdownlist>

Here, I am trying to set the default item after selecting an option from dropdown. When using setTimeout it is working but I got a review not to use it. Is there any alternative way to do this? Thanks.

Upvotes: 0

Views: 2264

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73731

You could do the following instead of calling setTimeout:

  • Set gridselectedValue to the new value
  • Call ChangeDetectorRef.detectChanges
  • Set gridselectedValue to the default value
constructor(private changeDetectorRef: ChangeDetectorRef) {}

gridDisplay(obj: { text: string; value: string }) {
  this.gridselectedValue = obj;                   // <-- set new selected value
  this.changeDetectorRef.detectChanges();         // <-- run change detection
  this.gridselectedValue = this.griddefaultItem;  // <-- reset selected value
  // Do more processing here...
}

See this stackblitz for a demo.

Upvotes: 1

Related Questions