Issue
I have an Angular 16 Project. 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++).
"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
Answered By - MoxxiManagarm
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.