如果我在Typescript文件中有一个布尔值,如何在相应的HTML文件中访问它?

时间:2019-06-21 17:26:37

标签: html angular typescript boolean

我有一个在Angular组件的Typescript文件中设置的布尔值,并且我只想在布尔值为true时才在HTML文件中显示一些文本。我怎样才能做到这一点?

打字稿:

this.displayButton = true;

HTML:

<script>
    if ({{ displayButton }} = true) {
        document.write("<span>Some text</span>");
    } else {
        document.write("<span>Some other text</span>");
    }
</script>

3 个答案:

答案 0 :(得分:2)

您可以使用*ngIf结构指令:

<div *ngIf="displayButton">
<span>Some text</span>

<div *ngIf="!displayButton">
<span>Some other text</span>

或者仅一行(如@Plixxer所指出的那样):

<span>{{ displayButton ? 'some text' : 'some other text'}}</span>

答案 1 :(得分:0)

我认为您遇到的问题是您正在检查布尔值的错误值。您应该使用两个'='而不是一个。

示例:

如果({{displayButton}} == 是)

答案 2 :(得分:0)

您可以在标签中使用if条件

<button *ngIf="this.displayButton =='true'"  >      
            </button>

或者您可以使用一个函数,如果变量设置为true,则该函数返回true

<div *ngIf="isResult()">
</div>

isResult()是将从.ts文件返回布尔值的函数