fangio
fangio

Reputation: 1786

Angular 4 Execute Function when html fully loaded

I have a problem with asynchronous HTTP calls in Angular 4 using typescript/components... I create an array of objects, and in the HTML I have checkboxes next to the objects. Now I want certain objects to be checked, by executing a function in angular. However when I do

 (document.getElementById(id) as HTMLInputElement).checked = true;

In my component.ts. It can't find the element however when I do the same code in a function that executes when you push a button it works. So the problem is that the HTML is not fully loaded when I execute the function. How can I make sure the HTML is fully loaded?

Upvotes: 1

Views: 4266

Answers (2)

Sidharth
Sidharth

Reputation: 1

Consider this as the last option since I wouldn't recommend direct DOM manipulation in Angular. But if you are still facing the issue, use can use my solution as a work around.

In constructor ,

let interval = setInterval(() => {
        let flag = self.checkFunction();
        if (flag)
            clearInterval(interval);
    }, 100)

Now create the function

checkFunction() {
    if(document.getElementById(id)){
         (document.getElementById(id) as HTMLInputElement).checked = true;
         return true;
    }
    return false;
}

Upvotes: 0

kimy82
kimy82

Reputation: 4465

Yeah You shouldn't be manipulating the DOM.

  • Tag your HTML element in the html using hash.

    <input ... #inputname />

  • Retrieved in the ts controller component.

    @ViewChild('inputname') theinput;

  • Check after view init. ngAfterViewInit if it is checked

    ngAfterViewInit() { ... (this.form as HTMLInputElement).checked ... }

Upvotes: 1

Related Questions