简体   繁体   English

angular4 html根据某些变量动态变化

[英]angular4 html changes dynamically according to some variables

HTML file: HTML档案:

<div [hidden]="isshow">
  <h1>this is a</h1>
</div>
<div [hidden]="!isshow">
 <h1>this is b</h1>
</div>

component.ts: component.ts:

  public get isshow() {
    return (this._state === 'ready');
  }

The state value is changed by an EventListener, and will change from "connecting" to "ready". 状态值由EventListener更改,并且将从“正在连接”更改为“就绪”。

What I want is to show "this is a" at the beginning then change to "this is b" when state is "ready", but looks it doesn't work. 我想要的是在开始时显示“ this is a”,然后在状态为“ ready”时更改为“ this is b”,但看起来不起作用。 *ngIf doesn't work either. * ngIf也不起作用。 What should I do? 我该怎么办? Subscribe it? 订阅吗?

If using a timer,the page will change, such as : 如果使用计时器,页面将更改,例如:

 setTimeout(()=>{this._state = 'ready'},30000); 

But I don't want to use Timer. 但是我不想使用计时器。

Thanks in advance. 提前致谢。

Try this, there is a small mistake in your code. 试试看,您的代码中有一个小错误。 if isshow is a function then you should pass it with brackets as mentioned below. 如果isshow是一个函数,则应使用方括号将其传递,如下所述。

template 模板

<div [hidden]="isshow()">
      <h1>this is a</h1>
    </div>
    <div [hidden]="!isshow()">
     <h1>this is b</h1>
    </div>

component 零件

isshow() {
    return (this._state === 'ready');
  }

Demo 演示版

I hope this will help you. 我希望这能帮到您。 If you have any doubts or suggestions let me know. 如果您有任何疑问或建议,请告诉我。

it's often better to toggle an element's presence using *ngIf . 通常最好使用*ngIf来切换元素的存在。

  <div *ngIf="isshow()">
      <h1>this is a</h1>
    </div>
    <div *ngIf="!isshow()">
     <h1>this is b</h1>
    </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM