Only show a single li element in CSS at a time

I'm working with Angular 2 and I have a list:

    <ul>
        <li *ngFor="let show of (ann)">
            {{show}}
        </li>
    </ul>

I want to show one item from the list every 3 seconds in an infinite loop.

Here's my array:

ann: Array<any> = [
    {
      name: "ABC"
    },
    {
      name: "DEF"
    },
    {
      name: "ZZZ"
    }
];
  • First 3 seconds: display ABC
  • Next 3 seconds: display DEF, while ABC disappears
  • Following 3 seconds: display ZZZ, replacing DEF
  • After 3 seconds: display ABC again and continue in an infinite loop

How can I achieve this using CSS?

Answer №1

Implementing animations in Angular 2 can enhance the user experience.

To see a live demonstration, visit this link

app.component.ts

@Component({
  selector: 'my-app',
  animations: [
    trigger('displayName', [
      state('in', style({ opacity: 1, transform: 'translateY(0)' })),
      state('out', style({ opacity: 0, display: "none", transform: 'translateY(100%)' })),
      transition('in => out', [
        style({ transform: 'translateY(0)', opacity: 1 }),
        animate('0.5s', style({ transform: 'translateY(100%)', opacity: 0 }))
      ]),
      transition('out => in', [
        style({ transform: 'translateY(100%)', opacity: 0 }),
        animate('0.5s ease-out', style({ transform: 'translateY(0)', opacity: 1 }))
      ])
    ])
  ]
})
export class App {
  name:string;
  currentIndex: number;

  students: [] = [
    {
      name: "Alice",
      animationState: 'in'
    },
    {
      name: "Bob",
      animationState: 'out'
    },
    {
      name: "Charlie",
      animationState: 'out'
    }
  ];

  constructor() {
    this.name = 'Angular Animations';
    this.currentIndex = 0;
  }

  ngOnInit() {
    setInterval((function(){
      console.log(this.currentIndex);
      this.students[this.currentIndex].animationState = 'out';
      this.currentIndex++;
      if(this.currentIndex >= this.students.length) {
        this.currentIndex = 0;
      }
      this.students[this.currentIndex].animationState = 'in';
    }).bind(this), 4000);
  }
}

html

<div>
  <h2>Greetings, {{name}}!</h2>
</div>
<div *ngFor="let student of students" [@displayName]="student.animationState">
    Hello, {{student.name}}
</div>

Answer №2

To achieve this in the template, you can utilize Rxjs.

    <div>
      <h2>Greetings {{name}}</h2>
    </div>
<div *ngFor="let pupil of $students | async">
    {{pupil.name}}
</div>

And in the component:

 students: Array<any> = [
    {
      name: "Alan"
    },
    {
      name: "Jake"
    },
    {
      name: "Harry"
    },
    {
      name: "Susan"
    },
    {
      name: "Sarah"
    },
    {
      name: "Esther"
    }
];

  constructor() {
    this.name = 'Angular2'
    var timer = 0;
    this.$students = Observable.from([[], ...this.students])
    .mergeMap(x => Observable.timer(timer++ * 1000).map(y => x))
    .scan((acc, curr, seed) => {
      acc.push(curr);
      return acc;
    });
  }

Check out the demo here

Answer №3

Based on my understanding of your request, it seems like you are interested in a format similar to the following:

li {
  opacity: 0;
  animation: display 10s infinite;
}

li:nth-child(1) {
  animation-delay: 1s;
}
li:nth-child(2) {
  animation-delay: 3s;
}
li:nth-child(3) {
  animation-delay: 5s;
}
li:nth-child(4) {
  animation-delay: 7s;
}
li:nth-child(5) {
  animation-delay: 9s;
}

@keyframes display {
  0% {  opacity: 1  }
  20% { opacity: 0  }
}
<ul class="num-1">
  <li>Jake</li>
  <li>Esther</li>
  <li>John</li>
  <li>Ann</li>
  <li>Someone</li>
</ul>

Alternatively, you may prefer the following arrangement:

li {
  opacity: 0;
  animation: display 10s infinite;
}

li:nth-child(1) {
  animation-delay: 1s;
}
li:nth-child(2) {
  animation-delay: 3s;
}
li:nth-child(3) {
  animation-delay: 5s;
}
li:nth-child(4) {
  animation-delay: 7s;
}
li:nth-child(5) {
  animation-delay: 9s;
}

@keyframes display {
  20% {  opacity: 1  }
  30% { opacity: 0  }
}
<ul class="num-1">
  <li>Jake</li>
  <li>Esther</li>
  <li>John</li>
  <li>Ann</li>
  <li>Someone</li>
</ul>

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

Maintain the visibility of the jQuery dropdown menu even when navigating to a different page within the

I am experiencing an issue with my dropdown menu. Whenever I click on a "dropdown link", it opens another page on my website, but the menu closes in the process. I want to ensure that the menu stays open and highlights the clicked "dropdown link" in bold. ...

What is the best way to include some white space around a paragraph?

Can anyone help me figure out how to add margins to my paragraphs with borders on a website? I've tried using margin in CSS, but it's not working. Here is the HTML code I am using: body{ margin:0px; font-family:Calibri; background ...

Tips for implementing loading functionality with Interceptor in Angular version 17

I am attempting to implement an interceptor in the latest version of Angular 17. export const loadingInterceptor: HttpInterceptorFn = (req, next,) => { const loadingService = inject(LoadingService); loadingService.show(); return next(req).pipe( finaliz ...

Adjusting the duration of the timeout for HTTP requests using Node.js alongside Angular 4 or Express

I am facing an issue with a request being sent from an Angular 4 app (which utilizes Electron that runs on Chromium) to a bottleneck server built in Node.js/Express. The server takes approximately 10 minutes to process the request, but the default timeout ...

Custom AG Grid PCF Control - Styling without the need for a separate CSS loader

Struggling to implement AG Grid in a PCF control because CSS loaders are not supported. Are there any alternatives for adding CSS without using CSS loaders? Thanks. Source - "‎06-22-2020 11:38 AM Ah I see - the only supported way of including CSS ...

When clicking on HTML input fields, they do not receive focus

I am facing a puzzling issue where I am unable to access the input fields and textareas on my HTML form. The JS, HTML, and CSS files are too large for me to share here. Could someone provide guidance on what steps to take when troubleshooting this unusual ...

Tips on preventing the constant shifting of my webpage div elements when resizing the browser

Whenever I resize my webpage browser, the 3 text input boxes move and overlap, causing the page layout to become messy. View of The Browser in full screen (normal) View of The Browser when it's smaller (not normal) As a beginner programmer, I have ...

The server will only load on Safari's localhost and not on Chrome's

My Node server is only working in Safari when using http://localhost:8000, but not in Chrome. Interestingly, using 127.0.0.1:8000 works on both browsers. I'm puzzled as to why localhost doesn't work in Chrome even though pinging localhost in my t ...

Guide to Embedding an External CSS Stylesheet

I have made edits because the link to the "previously answered solution" is not helpful. Find additional information attached at the end of this question Original Query All my HTML pages contain two links to external style sheets. As a result, I am look ...

Utilizing PHP to create an interactive website

As a novice PHP developer, I took to Google in search of tutorials on creating dynamic PHP websites. What I found was that many tutorials used the $_GET variable to manipulate URLs and make them appear like this: example.com/?page=home example.com/?page= ...

Utilizing a background image in the slick slider

<div id="largeCarousel" style="display:inline-block; float:right;"> <div class="homepage-item" style="padding-bottom:52%; position:relative; box-sizing:border-box;"> <div id="largeCarouselContent" style="position:absolute ...

Arrange a cluster of CSS table cells onto a fresh line

Currently, I am exploring CSS properties to create the visual appearance of a table using two levels of DOM elements. The highest-level element wraps around its child elements, which are styled to resemble a flat list. For example: <div class="t"> ...

Creating a Runescape Tracker: What essentials should I include?

Hello everyone, I am a beginner in the world of programming and I am excited to learn. I have heard that the best way to learn is by working on a project. I have always been interested in creating a Skill Tracker for my clan. Can you offer any advice on wh ...

The console errors in the test are being triggered by the Angular setTimeout() call within the component, despite the test still passing successfully

I am currently experimenting with a click action in Angular 7 using an anchor tag Below is the markup for the anchor tag in my component <div id="region-start" class="timeline-region"> <div class="row"> <div class="col-12 col-md- ...

Designing the appearance of a button in a filefield xtype

I am currently working on a web application where users can upload photos using a fileField. I have been struggling to style the button for this feature, as my attempts so far have not been successful. Initially, I tried using the element inspector to iden ...

Prevent mat-table rows from collapsing when new data is added (Angular Material)

I'm currently in the process of creating an application that relies on real-time data updates every few seconds. The app utilizes a mat-table, which includes another mat-table within a collapsible row. While the collapsing functionality works properly ...

Encountered an error while attempting to upload image to Web API using Angular

I'm encountering an issue when attempting to upload a picture, as I am unable to successfully send the picture file to my backend (.net core) using Angular. Every time I make a post request, I consistently face the Error:HttpErrorResponse error. It se ...

When utilizing narrow resolutions, header letters may overlap each other

As I integrate bootstrap into my website, I've noticed that when the resolution is narrow, my header overlaps. If the header is of a small size, like the typical H1 size, everything looks fine. However, when using a larger size (see CSS below), the is ...

The appearance of online and local websites varies on a single screen and browser

My current dilemma revolves around the difference in appearance of my website when viewed locally versus online. Both versions are connected to the same git repository and use the same css file. Interestingly, I can view the page on both my local machine a ...

Tips for applying a CSS class with a smooth fade-out effect

In my Angular project, I am working on creating a custom notification component. Here is the template code I have so far: <aside *ngFor="let message of messages "> <div class="notification" style="position:fixed"> {{message.conten ...