简体   繁体   中英

How to stop scrolling when there is no content to display in angular 6?

I am making angular 6 application where i am making a scrollable divs which has,

HTML:

<button class="lefty paddle" id="left-button"> PREVIOUS </button>
  <div class="container">
    <div class="inner" style="background:red"></div>
    <div class="inner" style="background:green"></div>
    <div class="inner" style="background:blue"></div>
    <div class="inner" style="background:yellow"></div>
    <div class="inner" style="background:orange"></div>
  </div>
<button class="righty paddle" id="right-button"> NEXT </button>

TS:

  ngOnInit() {
    const container = document.querySelector(".container");
const lefty = document.querySelector(".lefty");
let translate = 0;

lefty.addEventListener("click", function() {
    translate += 200;
    container.style.transform = "translateX(" + translate + "px" + ")";
});

const righty = document.querySelector(".righty");
righty.addEventListener("click", function() {
    translate -= 200;
    container.style.transform = "translateX(" + translate + "px" + ")";
});
  }

Working Stckblitz: https://stackblitz.com/edit/angular-mncf26

In this working demo you can see there is next and previous button which will make translate of 200px either to right or left as per the click..

Here if the click was made either in left or right even if there is no content it is scrolling 200px either side..

How can i stop the scroll if there is no content to display??

This is tricky because you are moving the container in a reverse direction, so you have to play on the negative values of your variables.

I made a quick stackblitz showing that (and I changed your code a bit to simplify it, sorry), tell me if it is what you want :

<button class="lefty paddle" 
  (click)="translateValue = translateValue + 200" 
  [disabled]="-translateValue <= 0"> PREVIOUS </button>

  <div class="container" #container [ngStyle]="getStyle">
    <div class="inner" *ngFor="let item of elements" [style.background]="item" #items></div>
  </div>

<button class="righty paddle" 
  (click)="translateValue = translateValue - 200"
  [disabled]="-translateValue >= container.offsetWidth"> NEXT </button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM