如何创建具有布尔值和特定ID的按钮?

时间:2019-05-28 15:31:02

标签: angular ngfor codemirror

我目前正在编码一个组件以显示文档,例如qt doc(https://doc.qt.io/qt-5/qstring.html),并且我正在使用CodeMirror来显示代码示例。

我正在使用Angular 2:

<div *ngFor="let method of methods" style="background-color: inherit; margin: left">
      <div class="content" style="position: relative;">

        <p class="title" style="font-size: 150%; text-decoration: underline" id="{{method.id}}">
          {{ method?.name }}
        </p>
        <br/>
        <p class="description" *ngIf="method"  [innerHtml]="method.description | textToHtml"></p>
        <div class="markdown" markdownMethodDocumentationRenderer [text]="method.documentation"></div>
        <button class="button" *ngIf="!showCode" (click)="showCloseExample()">Show example</button>
        <button class="button" *ngIf="showCode" (click)="showCloseExample()">Close example</button>
        <div *ngIf="showCode">
          <app-code-mirror [data]="method.documentation"></app-code-mirror>
        </div>
        <br/>
        <hr>
        <br/>
      </div>
    </div>

我创建了一个按钮来显示或隐藏内部带有CodeMirror组件的div,但是当我单击此按钮时,它将打开每个示例。 我认为是因为它在ngFor上。 当我单击此按钮时,我只想打开一个div,而不是全部。

2 个答案:

答案 0 :(得分:0)

您将不得不使用showCode标志的数组或将标志添加到方法变量。现在,您正在使用单个标志showCode来显示/隐藏*ngFor中的每个元素。

答案 1 :(得分:0)

代码的问题是您要更改一个变量 showCode 。您还正在观看 showCode 变量,并在每个片段更改时打开/关闭它们。

有很多解决此问题的方法,其中一种如下:

方法数组的每个对象中添加一个新的布尔值。像您一样叫它 showCode 。现在,每个方法都有一个showCode标志。您将拥有ngIf="showCode"而不是ngIf="method.showCode"

现在,您可以执行类似(click)="showCloseExample()"的操作,而不是(click)="method.showCode = !method.showCode"。 (我相信这是Angular中正确的语法,如果没有,请将其绑定到函数并传递方法的索引,然后更新方法showCode标志)