Failed to get item by ID in ngIf

I played a little with A2, and I understand that my problem is that everything is initializing and starting inside A2 and because of *ngIfin html, but I don’t understand why and how to get the 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>

I don’t understand why even in ngOnInit console.logof test1returns nullwhere as test2returns the element. I know this because it is inside *ngIf, but I don’t understand why or what to do to access this element after it is displayed, so that I can interact with it as part of the google maps API

EDIT Updated code that I would foolishly exclude.

+4
1

DOM element ngAfterViewInit , angular context , DOM element(with Angular context) to be fully available ngAfterViewInit .

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


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

Source: https://habr.com/ru/post/1669016/


All Articles