Angular之不能获取html某id

前言

    在做项目中,业务为页面加载中根据从后台传过来的不同数据情况来确定页面的button的样式,但是使用ngOnInit()来加载方法,却一直显示找不到button的id,获取不到button。


原因

    在ts中我是使用document.getElementById(“id”),来获取button,但是是放在初始加载函数中即ngOnInit()中,所以判断页面初始加载函数和页面渲染是同时进行的,所以在实现初始加载函数的时候html页面并没有渲染完成,因此,不能找到button的id。


解决办法

   解决办法超级多,下面整理一下我找到的解决办法,不过我是用ngSwitch解决的。

   1.延迟加载,可以给定一个时间,这个时间之后再去加载,也可以判断在某个事件完成之后再去加载。主要是用Directive。具体可以参考这篇博客在AngularJS中实现一个延迟加载的Directive

   2.ngStyle,使用angular独有的ngStyle来判断什么时候用什么样式。

   3.ngSwitch,就是我使用的解决办法,其实上边ngStyle的原理和它没有什么区别。下面将详细讲解一下!


ngSwith是什么

    有时候你需要根据一个给定的条件来渲染不同的元素,而且情况多种多样,这时候如果你使用ngIf语句的话,那样代码会非常冗余,所以这时候ngSwitch出现。、

    ngSwitch背后的思想就是对表达式进行一次求值,然后根据其结果来决定如何显示指令内的嵌套元素。一旦有了结果,我们就可以使用:

     1.ngSwitchCase指令描述已知结果。

     2.ngSwitchDefault:指令处理所有其他未知的情况。


如何解决我的问题

    这时候我在ts中声明一个变量,然后根据后端传回来的不同数据情况去给变量赋不同的值。html页面用ngSwitch根据变量不同的值去渲染button不同的样式。详细代码如下:

HTML代码   

    <!-- 根据状态ID来决定按钮的显示 -->
        <div [ngSwitch]="statusID">
            <!-- 只显示收了它按钮 -->
            <div *ngSwitchCase="0">
                <!-- <button pButton type="button" id="buy" (click)="buyGoods()" label="立即购买" style="float:right;display: block;" class="ui-button-success"></button> -->
                <button id="buy" style="float:right;display: block;" (click)="buyGoods()">收了它</button>
                <!-- <button pButton type="button" id="delivery" (click)="deliveryGoods()" label="收货" style="float:right;display: none;" class="ui-button-success"></button> -->
                <button id="delivery" style="float: right;;display:none;" (click)="deliveryGoods()">收货</button>
            </div>
            <!-- 两个按钮都不显示 -->
            <div *ngSwitchCase="1">
                    <button id="buy" style="float:right;display: none;" (click)="buyGoods()">收了它</button>
                    <button id="delivery" style="float:right;display:none;" (click)="deliveryGoods()">收货</button>
            </div>
            <!-- 只显示收货按钮 -->
            <div *ngSwitchCase="2">
                    <button id="buy" style="float:right;display:none;" (click)="buyGoods()">收了它</button>
                    &nbsp;&nbsp;&nbsp;
                    <button id="delivery" style="float:right;display:block;" (click)="deliveryGoods()">收货</button>
            </div>        
        </div>

猜你喜欢

转载自blog.csdn.net/weienjun/article/details/80194558