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

Is there a way to remove a specific row from both an HTML table and a MySQL database using CodeIgniter?

Just diving into CodeIgniter and successfully retrieved data from MySQL to display in an HTML table. Now, the challenge is to delete specific rows in MySQL. Imagine a scenario where there are 10 rows in the table, each accompanied by a checkbox, and a Del ...

Error: Reactjs - Attempting to access the 'name' property of an undefined variable

As I continue to learn about React, I have been experimenting with props in my code. However, I encountered an error where the prop is appearing as undefined. This issue has left me puzzled since I am still at a basic level of understanding React. If anyo ...

The reason behind the clickable issue with my duplicate <ion-select>

I've been working on a form using HTML, CSS, and JavaScript where I implemented an "Add" button to duplicate the form. The issue arises with the ion-select element within the duplicated form. While the original form displays all predefined options upo ...

What is the most efficient method for embedding a YouTube video into a <video> tag using React?

I tried embedding a YouTube video using an HTML5 tag, but encountered an error <div className={classes.VideoContainer}> <video className={classes.movieInfo__trailer} src="https://www.youtube.com/watch?v=V3hy2aLQFrI" ...

Unable to scroll down an overlay window using Selenium with Python

When using Quora, I am trying to scroll to the bottom of the window that appears when I click on the "View upvoters" button in order to access all the names of those who have upvoted. However, the code for scrolling down a standard browser window doesn&apo ...

Error code 0 occurs in jQuery AJAX when there is an issue with the communication between the client

Currently delving into the world of ASP.NET and wanted to create a basic website utilizing ajax to retrieve a simple string from the server. Upon running the ajax request, an error message pops up stating An error occurred: 0 error Here's a glimpse ...

Is it possible to refresh the chat-box using PHP?

I recently created a chat box application using PHP, but I'm facing an issue with its automatic reload functionality. Is there a way to implement auto-reload in PHP itself, or would it be better to restructure the system to utilize AJAX? Additionally, ...

Unraveling functions from a JavaScript promise in a web application using ExpressJS and NeDB

I have successfully implemented code that retrieves all users from my neDB-promisses: const fetchAllUsers = (res) => { db.find({}) .sort({ name: 1 }) .exec() .then( (content) => { res.status(2 ...

What is the best way to allow my limit to be as greedy as possible?

I'm facing an issue with the code below where it currently only matches MN. How can I modify it to also match KDMN? var str = ' New York Stock Exchange (NYSE) under the symbol "KDMN."'; var patt = new RegExp("symbol.+([ ...

Troubleshooting issues with the IE flexible box model functionality

Working on incorporating the flexible box model into my website has been a bit challenging. It seems to function well in webkit-based browsers like Chrome and Safari, but I'm running into issues with Mozilla, Opera, and most notably Internet Explorer. ...

What is the method for showing the number of characters in a string within a textfield by utilizing events in Angular

I have been working on a project that requires me to calculate and display the length of a string entered into a text field using Events. There is an additional condition where the string length must be greater than 4 in order for the length to be displaye ...

I am struggling to display an array of objects retrieved from the server in the UI using AngularJS

I am receiving an array of objects as a JSON from the server. When I try to access my service URI from HTML, I encounter the following array in my console: "angular.js:13920 Error: [$resource:badcfg] http://errors.angularjs.org/1.5.8/$resource/badcfg?p0= ...

Guide on creating a function in PHP that takes a string input and outputs it in JSON format

Here is an illustration of a data structure that specifies the color of different fruits: array( "red" => array("apple, strawberry"), "yellow" => array("lemon", "ripe mango") ) Create a function called getFruits, which takes a color as input ...

Initial page load experiencing issues with paroller.js functionality

Upon hard refreshing the page in the middle section, there seems to be an issue with the paroller js transform: translateY(); CSS effect not functioning properly on the <div class="col col-6" data-paroller-factor="0.4" data-paroller-type="foreground" da ...

The PHP page is not receiving the variable passed through AJAX

Within the following code snippet, there seems to be an issue with accessing the dataString variable in the comment.php page. To retrieve the variable name, I utilized $_POST['name']. $(document).ready(function(){ $("#submit").click( function() ...

Error occurred when attempting to fetch data from a nested JSON object in React/Next.JS

Having trouble retrieving data from my API and encountering this error message. I suspect it may be related to the JSON structure. Interestingly, when using a different URL with nested arrays, it works fine. However, my current data is not cooperating. Any ...

What is the best way to create a grid item that maximizes the available space in ReactJS Material-UI?

Currently, I am working with the material-ui grid system in a reactjs project. In a column grid container layout, my goal is to display two grid items and have a third item fill up the remaining space between them. Essentially, I want it to look like this: ...

Is it possible to utilize the useRef Hook for the purpose of storing and accessing previous state values?

If you have already implemented the useState and useEffect Hooks for maintaining previous state, another approach is to utilize the useRef Hook to track previous state values as well. ...

Customize Bottom Navigation Bar in React Navigation based on User Roles

Is it possible to dynamically hide an item in the react-navigation bottom navigation bar based on a specific condition? For example, if this.state.show == true This is what I've attempted so far: const Main = createBottomTabNavigator( { Home: { ...

The error code TS2345 indicates that the argument '{ read: typeof ElementRef; }' cannot be assigned to the parameter '{ read?: any; static: boolean; }'

Currently in the process of updating my Angular application from version 7 to version 8. Upon running ng serve, I encounter the following error: Error TS2739: Type '{}' is missing the following properties from type 'EmployeeModel': stat ...