I'm encountering a simple problem which has a hacky solution of setTimeout(...,0)
.
Looking at this simple code :
@Component({
selector: 'my-app',
template: `
<div>
<input value='Fill Data' type='button' (click)='fill()'/>
<span *ngFor="let o of Items" class='mySpan'>Span To Detect<br></span>
</div>
`,
})
export class App {
Items:Array<number> = new Array<number>();
fill()
{
this.Items = [1,2,3,4,5,6,7,8,9,10]
this.analyzeDom(); //this has to run here
}
analyzeDom()
{
alert($("div .mySpan").length) // "0"
//BUT if I set this hacky trick , it works
// setTimeout(function (){ alert($("div .mySpan").length)},0) // "10"
}
}
If I click the button , the alert shows "0". I understand why it's happening. It's becuase Angular didn't complete its cycle to actually populate the ngFor
.
However - doing this trick with setTimeout(..,0)
seems a bit hacky to me and I prefer not to trust on it.
Question:
What is the right way to "wait for operation" in Angular ? (so that I'll see "10") ?
Plnkr