1

Scenario (DOM):

<div *ngFor="let one of many">
    <span [innerHtml]="one"></span>
</div>

Scenario (Controller):

let many = [];
let timer = 60;
setInterval(() => timer--, 1000);
many.push("this is a selection WITH a {{timer}}");
many.push("this is a selection WITHOUT a timer");

So basically theres an array "many" which can have many strings created dynamically pushed into it and also some of the strings passed into "many" have countdowns and others do not. Is there a way to pass a model into the DOM via a string as shown above and have the timer update? And if its doable how can it be achieved.

I really hope this isnt one of those "gotchas" thats soooo obvious.

Gracias

1 Answer 1

3

PLUNKER

This is kind of a 'hacky' solution but it works and you don't need to create extra components.

First, change your template to this:

<div *ngFor="let one of many">
    {{one.replace('[timer]', timer)}}
</div>

Second, declare timer and many as class variables:

export class YourComponent {
    timer:number=60;
    many:string[];

    (...)
}

Lastly, when adding new lines to many, whenever you want to include timer use [timer] instead of {{timer}}.

You can change [timer] to whatever you want.

Sign up to request clarification or add additional context in comments.

6 Comments

Not really. timers value will be appended once and Angulars Change Detection wont called on it to update the DOM in subsequent updates.
Ah, sorry, I guess I didn't understand the question properly. I thought you asked how to make the newly added elements properly display in the DOM. Is the question about the timer then? You want to know how to run the timer periodically? If not, please clarify so I can help you out.
Yes indeed the question is about the timer, and yes, it seems like I am not framing the question properly so let me explain broadly. I want that timer to be updateable but I dont want to declare it the usual way in a component or the DOM because the array "many" will receive other strings. So the output could look something like Hi I am a timer (60-59-58....0) <-( this is the countdown timer dynamically passed to "many") Hello we are waiting for you. <- (A string dynamically passed to "many") Hi whats up? <- (Another string dynamically passed to "many")
Ok, I understand now, gonna update my answer, give me 5.
Ahhhh!!! Was actually supposed to use setInterval there. Thanks. Will test and revert.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.