Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了angular – 无法在ngIf内按ID获取元素大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经玩了A2一段时间了,我明白我的问题是由于所有内容初始化并在A2中运行的顺序,并且由于html中的* ngIf,但我不明白的是为什么或如何得到我想要的结果.

使用以下测试组件:

@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.test@R_696_9260@ce.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
    } 
}

和test.component.html

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

我不明白为什么,即使在NgOnInit中,test1的console.log返回null,因为test2返回元素.我知道这是因它在* ngIf中,但我不明白为什么或一旦它被渲染后访问该元素该怎么做@R_598_9447@作为谷歌地图API的一部分与它进行交互

编辑更新了一些我愚蠢地排除的代码.

解决方法

如果在该元素上使用任何角度上下文,则可以在NgAfterViewInit生命周期钩子中引用DOM元素.您可以期望DOM元素(具有Angular上下文)在NgAfterViewInit生命周期钩子中完全可用.

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


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

大佬总结

以上是大佬教程为你收集整理的angular – 无法在ngIf内按ID获取元素全部内容,希望文章能够帮你解决angular – 无法在ngIf内按ID获取元素所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。