Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

angular - Question on toggling a button on mat table

How can I change the button on the row I clicked on only?

On my ts file: arrow = 'fa fa-caret-right fa-lg';

toggleArrow() {
  if (this.arrow === 'fa fa-caret-right fa-lg') {
    this.arrow = 'fa fa-sort-desc fa-lg';
  } else {
  this.arrow = 'fa fa-caret-right fa-lg';
  }
}

On my html file, that's how I define my action column:

<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef>Actions</th>
<td mat-cell *matCellDef="let element">
<!--edit button-->
<button type="button" class="btn btn-default" aria-label="Left Align">
<span class="fa fa-pencil-square-o fa-lg" aria-hidden="true"></span>
</button>
<!-- arrow button-->
<button type="button" class="btn btn-default" aria-label="Left Align"
(click)="toggleArrow()">
<span class="{{arrow}}" aria-hidden="true"></span>
</button>
</td>
</ng-container>

If I click on the right arrow, it should changes to down arrow

However, every row got changed.

question from:https://stackoverflow.com/questions/65600641/question-on-toggling-a-button-on-mat-table

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A better solution would be to store the id of the element that you clicked on, and then if the stored id is the same as the element shown or the corresponding icon, see here you have an example with material icon but the logic is the same for your case.

Example

elementId: number;

toggleArrow(id: number) {
  if (id === this.elementId) {
    this.elementId = null;
  } else {
    this.elementId = id;
  }
}

<ng-container matColumnDef="actions">
   <th mat-header-cell *matHeaderCellDef>Actions</th>
   <td mat-cell *matCellDef="let element">
     <!--edit button-->
     <button type="button" class="btn btn-default" aria-label="Left Align">
        <span class="fa fa-pencil-square-o fa-lg" aria-hidden="true"></span>
     </button>
     <!-- arrow button-->
    <button type="button" class="btn btn-default" aria-label="Left Align"
           (click)="toggleArrow()">
       <span  [ngClass]="{
                         'fa fa-sort-desc fa-lg': element.id === elementId,
                         'fa fa-caret-right fa-lg': element.id !== elementId}" 
            aria-hidden="true"> 
      </span>
    </button>
   </td>
</ng-container>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...