Search code examples
angularngforcodemirror

How can i create a button with boolean and a specific id?


I am currently coding a component to display documentation, like qt doc (https://doc.qt.io/qt-5/qstring.html) and I am using CodeMirror to display a code example.

I am using 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>

I created a button to show or hide a div with a CodeMirror component inside but when I click this button, it opens every examples. I think it's because it's on an ngFor. When I click this button, I want to open only one div and not all.


Solution

  • The problem with your code is that you are changing one variable showCode. You are also watching that showCode variable, and opening/closing each of your snippets whenever it changes.

    There are many solutions for this problem, one of them being as follows:

    Add a new boolean in each object of your methods array. Lets call it showCode, as you did. Now each method has a showCode flag. Instead of ngIf="showCode", you will have ngIf="method.showCode".

    Now, instead of (click)="showCloseExample()", you can do something like (click)="method.showCode = !method.showCode". (I believe this is the right syntax in Angular, if not, bind it to a function and pass the index of the method, and then update methods showCode flag)