首页 > 解决方案 > 如何通过 Angular 8 中的 id 获取元素来更改类并更改 div 的样式

问题描述

如何通过角度 8 中的 getElementBy id 添加和删除类。当用户单击详细信息图标时,我想删除类“col-md-12”并添加“col-md-6”。

并更改另一个 div 的样式,例如 display: block。

组件.html

 <div class="col-md-12" id="demo">
      <div class="example-container mat-elevation-z8 mt-5">
        <table class="table table-striped">
          <tbody>
            <tr>
              <th>Points</th>
              <th>###</th>
            </tr>
            <tr *ngFor="let user of usersArray" >
              <td>
                {{user.score}}
              </td>
              <td>
                <i class="material-icons text-primary pointer" (click)="details()">account_circle</i>
              </td>
            </tr>
          </tbody>

        </table>

      </div>
    </div>

换课后,我想显示这个 div

  <div class="col-md-6" style="display: none;" >
        <div class="userDetails">
            <img src="../../assets/images/user.png">
            <span class="mx-3"> <b>Shubham Patil</b></span>
            <div class="example-container mat-elevation-z8 mt-4">
              <table class="table table-striped rounded">
                <tbody>
                  <tr>
                    <th>Topics</th>
                    <th>Points</th>
                  </tr>
                  <tr >
                    <td>
                      Why me
                    </td>
                    <td>
                      300
                    </td>
                  </tr>
                </tbody>
              </table>
              </div>
        </div>
    </div>

组件.ts

element: HTMLElement;

 details(){
    this.element = document.getElementById('demo').removeClass("col-md-12") as HTMLElement;
    this.element = document.getElementById('demo').addClass("col-md-6") as HTMLElement;
    console.log("change")
}

标签: angulartypescriptangular8

解决方案


试试这样:

在模板中:

<div class="col-md-12" id="demo" #demo>
   ...
   <td>
    <i class="material-icons text-primary pointer" (click)="details(demo)">account_circle</i>
   </td>
   ...
</div>

并在 .ts

details(elem: HTMLElement) {
  console.log(elem.className, 'before');
  elem.className = 'col-md-6';
  console.log(elem.className, 'after');
}

推荐阅读