Doug
Doug

Reputation: 547

Unable to get element by ID within ngIf

I have been playing with A2 for a little while now and I understand that my problem is due to the sequence in which everything initialises and runs within A2 and due to the *ngIf in the html but what I don't understand is why or how to get my desired result.

Using the following test component:

@Component({
    moduleId: module.id,
    selector: 'test',
    templateUrl: 'test.component.html' })

export class TestComponent implements OnInit {
    test: any;

    settest():void{ 
        //this.test = {test: 1}; --This works using ngAfterViewInit

        //This causes the console.log in ngAfterViewInit to be null
        this.route.params
            .switchMap((params: Params) => this.testService.getTest(params['id']))
            .subscribe(test => {
                this.test = test;
        });
    }

    ngOnInit(): void
    {
        this.settest();
        console.log(document.getElementById('test1')); --Null
        console.log(document.getElementById('test2')); -- Not NUll
    } 

    ngAfterViewInit(): void
    {
        console.log(document.getElementById('test1')); --Null
        console.log(document.getElementById('test2')); -- Not NUll
    } 
}

and test.component.html

<div *ngIf="test">
    <div id="test1"></div>
</div>
<div id="test2"></div>

What I don't understand is why, even in the ngOnInit the console.log of test1 returns null where as test2 returns the element. I know it is because its within the *ngIf, but I don't understand why or what to do to access that element once its rendered so I can interact with it as part of the google maps API

EDIT Updated some code that I'd foolishly excluded.

Upvotes: 5

Views: 5114

Answers (1)

micronyks
micronyks

Reputation: 55443

You can refer to a DOM element in ngAfterViewInit life cycle hook if you are using any angular context on that element. You can expect DOM element(with Angular context) to be fully available in ngAfterViewInit life cycle hook.

ngOnInit(): void
{
    this.settest();
    console.log(document.getElementById('test1'));   // not rendered
    console.log(document.getElementById('test2'));
} 


ngAfterViewInit(){
   console.log(document.getElementById('test1'));    // rendered
}

Upvotes: 5

Related Questions