Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How would you create a text in the template, which iterates visibly over an array of strings?

I need to change a word in a sentence, so it changes all the time and displays another word every tenth of a second.

In JS I would have done this:

let jobs = ["wordOne", "wordTwo", "wordThree", "wordFour", "wordFive"]
var elem = document.getElementById("ito");
var elem2 = document.getElementById("ito2");
var counter = 0;
setInterval(change, 100);

function change() {
    elem.innerHTML = jobs[counter];
    elem2.innerHTML = jobs[counter];
       counter++;
       if(counter >= jobs.length) { counter = 0; }
   }

But in Angular I don’t seem to be able to get the change detection do the same. I even tried putting this code in a pipe, but it won’t update the word at all.
I used a solution, where I just made a sentence, and gave it a marker in place where the word needs to be replaced (++replaced++).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"This is an example entsence, which contains ++replaced++ words."

>Solution :

Just use rxjs and the async pipe.

@Component({
  selector: 'my-app',
  standalone: true,
  imports: [AsyncPipe],
  template: `{{ job$ | async }}`,
})
export class App {
  private readonly jobs = [
    'wordOne',
    'wordTwo',
    'wordThree',
    'wordFour',
    'wordFive',
  ];
  protected job$ = interval(100).pipe(
    map((i) => this.jobs[i % this.jobs.length])
  );
}

See stackblitz:
https://stackblitz.com/edit/angular-1yjn8u?file=src%2Fmain.ts

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading