【问题标题】:Unable to get element by ID within ngIf无法通过 ngIf 中的 ID 获取元素
【发布时间】:2017-02-07 07:16:40
【问题描述】:

我玩 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.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
    } 
}

test.component.html

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

我不明白为什么,即使在 ngOnInit 中,test1console.log 返回 nulltest2 返回元素。我知道这是因为它在 *ngIf 内,但我不明白为什么或如何在渲染后访问该元素,以便我可以作为谷歌地图 API 的一部分与之交互

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

【问题讨论】:

    标签: angular getelementbyid angular-ng-if


    【解决方案1】:

    如果您在该元素上使用任何 angular context,则可以在 ngAfterViewInit 生命周期挂钩中引用 DOM element .您可以在 ngAfterViewInit 生命周期挂钩中期待 DOM element(with Angular context) to be fully available

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

    【讨论】:

    • 仍然返回 NULL,即使在 ngAfterViewInit 中也是如此。由于 api 调用的异步(我会用它来更新我的答案,因为我愚蠢地排除了它),所以我可以说更多地使用代码。如果我删除异步调用,则 ngAfterViewInit() 有效,如果我保留 subscribe,则无效。
    猜你喜欢
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    相关资源
    最近更新 更多