TheKeymaster
TheKeymaster

Reputation: 897

Angular - *ngIf is only checking after click for native element

I am trying to create a card collection that should be able to be scrolled from left to right with buttons. If the container with cards in it is too big, a button should appear and if I click the button, then a button for scrolling to the left should appear and the container should be scrolled. The issue now is that it seems like *ngIf is only checking after I click on another element.

The container looks something like that (this should be a playlist):

screenshot

I thought about maybe the element needs to be re-focused, so JavaScript knows "Hey, it seems like my scrollLeft changed", but that did not work.

I have these two buttons:

<button *ngIf="showLeftScroll()" mat-icon-button class="scroll-button-left" (click)="scrollLeft()"><mat-icon>keyboard_arrow_right</mat-icon></button>
<button *ngIf="isScrollable()" mat-icon-button class="scroll-button-right" (click)="scrollRight()"><mat-icon>keyboard_arrow_right</mat-icon></button>

And the methods are:

isScrollable() {
  const container = this.cardContainer.nativeElement;
  const isScrollable = container.offsetWidth < container.scrollWidth;
  const isNotAtTheEnd = container.offsetWidth + container.scrollLeft !== container.scrollWidth;
  return (isScrollable && isNotAtTheEnd);
}

showLeftScroll() {
  return this.cardContainer.nativeElement.scrollLeft > 0;
}

scrollRight() {
  this.cardContainer.nativeElement.scrollLeft += 600;
  this.cardContainer.nativeElement.focus();
}

scrollLeft() {
  this.cardContainer.nativeElement.scrollLeft -= 600;
  this.cardContainer.nativeElement.focus();
}

What happens at the moment?

I click the button for scrolling to the right, it scrolls to the right, but the button for scrolling left only appears if I click on any other element.

What should happen?

The button for scrolling to the left should be shown right at the moment when I click on the button for scrolling to the right.

Upvotes: 1

Views: 973

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73741

To force an immediate update of the *ngIf directive, call ChangeDetectorRef.detectChanges() at the end of the scrolling methods:

constructor(private changeDetectorRef: ChangeDetectorRef) { }

scrollRight() {
  this.cardContainer.nativeElement.scrollLeft += 600;
  this.changeDetectorRef.detectChanges();
}

scrollLeft() {
  this.cardContainer.nativeElement.scrollLeft -= 600;
  this.changeDetectorRef.detectChanges();
}

Upvotes: 2

Related Questions