Iterate endlessly over CSS styles in Angular 4

I'm looking to create a website background 'screensaver' by looping through an array of background URLs with a delay between switches.

Currently, I have the array stored in my .ts file and I am using the NgFor directive in my HTML. However, there are two main issues - there is no delay between image changes (resulting in the last one being displayed) and it does not continuously loop through the array.

In my .ts file:

  bgImgs = [
`url("/assets/img/friendship.jpeg")`,
`url("/assets/img/family.jpeg")`,
`url("/assets/img/health.jpeg")`,
`url("/assets/img/fatherson2.jpeg")`

In my .html file:

<div *ngFor="let bgImg of bgImgs">
  <div [style.backgroundImage]="bgImg" id="home" class="pt-5">

Answer №1

While there are potential alternative approaches using "rxjs," here is a basic solution:

export class App implements OnInit {
  private imageUrls: string[];
  private current: number = 0;
  currentImage: string;
  constructor() {
    this.imageUrls = [
      '//placehold.it/1280x720.jpg',
      '//placehold.it/1280x721.jpg',
      '//placehold.it/1280x722.jpg',
      '//placehold.it/1280x723.jpg'
    ];
    this.currentImage = this.imageUrls[0]
  }
  ngOnInit() {

    // Every second...
    Observable.interval(1000)
    .subscribe(x => {
      this.currentImage = `url(${this.imageUrls[this.current]})`;

      // Reset current to 0 if we're at the end of the array
      this.current == this.imageUrls.length - 1 ? (this.current = 0) : ++this.current;
    })
  }
}

If you wish to incorporate fading or other transitions, additional work may be necessary.

Plunk

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery Load - Oops! There seems to be a syntax error: Unexpected token <

Error: Uncaught SyntaxError: Unexpected token < I encountered the error message mentioned above while trying to execute a jQuery load function: $('#footer').load(UrlOfFooterContent); The variable UrlOfFooterContent holds the URL of an MVC c ...

Position a div in the center and add color to one side of the space

I am seeking a way to create a centered div with the left side filled with color, as shown in examples. I have devised two solutions without using flexbox, but both seem somewhat like hacks. body { margin: 0; padding: 0; } .header { width: ...

Unable to Trigger Jquery Scroll Event

I'm trying to figure out why a div is not appearing when the page is scrolled down. The issue is that my page body and most other elements have overflow hidden, except for a table that appears at a certain point on the page when a button is pressed. T ...

JavaScript in IE/Edge may not run correctly if it is loaded from the cache

I am facing a peculiar problem with Internet Explorer (IE) and Edge. Upon initially loading a page, everything functions perfectly fine. However, if I navigate away from the page to another page on the same website, JavaScript errors start showing up on th ...

Is there a method in AngularJS to compel TypeScript to generate functions instead of variables with IIFE during the compilation process with gulp-uglify?

My AngularJS controller looks like this: ArticleController.prototype = Object.create(BaseController.prototype); /* @ngInject */ function ArticleController (CommunicationService){ //Some code unrelated to the issue } I minified it using gulp: retur ...

How can I extract information from an HTML table using AngleSharp?

Seeking a way to extract song data from a playlist on a music streaming website This table contains song information: <tr class="song-row " data-id="ef713e30-ea6c-377d-a1a6-bc55ef61169c" data-song-type="7" data-subscription-links="true" data-index="0" ...

Error: Unable to access the 'nom_gr' property of null - encountered in Chrome

<ion-col col-9 class="sildes"> <ion-slides slidesPerView="{{nbPerPage}}" spaceBetween="5"> <ion-slide *ngFor="let slide of lesClassrooms; let i = index" (click)="saveCurrentSlide(i)"> ...

"When implementing an Ajax autorefresh feature, ensure you pass the necessary variables consistently to update the content. Don't overlook

My chat box consists of two frames... The first frame displays all the usernames, while the second frame shows the full chat when a user is clicked from the first frame. I need to reload the second frame every time to check for new messages from the send ...

The useEffect function is failing to execute, leading to an issue with an undefined variable

Attempting to retrieve a specific string with the help of useRouter, then utilizing that same string to access a particular document from Firebase is my current goal. This sequence of actions is supposed to take place within the confines of the useEffect f ...

Yarn combined with Webpack fails to execute post-compilation tasks

When using yarn and running yarn prod, I encountered the following error: https://i.stack.imgur.com/2emFk.jpg It seems to be stuck at this particular part of the code: mix.then(() => { execSync(`npm run rtlcss ${__dirname}/Assets/css/admin.css ${__dir ...

I am unable to pass a variable through a callback, and I cannot assign a promise to a

Currently, I am facing a challenge with my code where I need to loop through a hard-coded data set to determine the distance from a user-entered location using Google's web API. The issue lies in passing an ID variable down through the code so that I ...

Tips for showing more rows by clicking an icon within an Angular 2 table

When I click on the plus (+) button in the first column of each row, only one row expands. How can I modify it to expand multiple rows at a time? Thanks in advance. <div> <table class="table table-striped table-bordered"> <thead> ...

pictures showcased in a grid that dance and sway

Hey everyone, I wanted to ask about images on a website that have a unique effect when you hover over them. On the site follow your feet website, there is a grid section of destinations and when you move your mouse over a destination, it suddenly expands a ...

Add more functionality to the server.js script

I have the server.js file, which serves as the entry point for my Node application and is responsible for invoking three different functions (these functions are only called once when the server is up, such as creating child processes, validation, etc), wh ...

javascript implementing number formatting during keyup event

When I try to format a number in an input field on the keyup event, I receive a warning in my browser console that says "The specified value "5,545" cannot be parsed, or is out of range." The value in the input field also gets cleared. How can I solve this ...

What causes the data to flicker between the old and new values when the state is updated in ReactJS?

Currently, I am developing a single-page application that fetches data from the Star Wars API. In the character section of the project, the goal is to display characters per page with the ability to navigate to the next or previous pages by clicking on but ...

Extracting a precise data point stored in Mongo database

I have been struggling to extract a specific value from my MongoDB database in node.js. I have tried using both find() and findOne(), but I keep receiving an object-like output in the console. Here is the code snippet: const mongoose = require('mongoo ...

AngularJS property sorting: organize your list by name

I have a complicated structure that resembles: { 'street35':[ {'address154': 'name14'}, {'address244': 'name2'} ], 'street2':[ {'address15& ...

Implementing AJAX mysqli interaction in PHP following the MVC design pattern

Today I'm encountering yet another AJAX-related error. I am in the process of developing a user registration system using AJAX and PHP, following MVC architecture. Previously, I successfully built a login system without AJAX that functions flawlessl ...

Transmit an array using a GET Request

I am currently working on a project where I need to make a GET request from JavaScript to Python and pass a 2D array. Here is an example of the array: [["one", "two"],["foo", "bar"]] However, I am facing issues with passing this array correctly. In my Ja ...