how can i change class by get element by id in angular 8 and change the style of div
如何通过 Angular 8 中的 getElementBy id 添加和删除类。
当用户单击详细信息图标时,我想删除类 \\'col-md-12\\' 并添加 \\'col-md-6\\'。
并改变另一个 div 的样式,例如 display: block.
component.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <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 </td> </tr> </tbody> </table> |
在改变类之后,我想显示这个 div
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <img src="../../assets/images/user.png"> <span class="mx-3"> Shubham Patil</span> <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> |
组件.ts
1 2 3 4 5 6 7 | 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") } |
试试看:
在模板中:
1 2 3 4 5 | ... <td> <i class="material-icons text-primary pointer" (click)="details(demo)">account_circle </td> ... |
并在 .ts
1 2 3 4 5 | details(elem: HTMLElement) { console.log(elem.className, 'before'); elem.className = 'col-md-6'; console.log(elem.className, 'after'); } |
执行此操作的"Angular"方法是使用 Angular 的模板语言将组件文件中的变量绑定到模板。有关更多信息,请参阅 Angular 文档中的模板语法。
component.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <div id="demo" [class.col-md-12]="!isShowingDetails" [class.col-md-6]="isShowingDetails"> <!--"[class.my-class-name] syntax to dynamically add or remove classes based on if the value assigned to the property is true/false --> ... <tr *ngFor="let user of usersArray"> <td> <i class="material-icons" (click)="showDetails()">account_circle </td> </tr> ... <!--ADDED *ngIf directive to show and hide details HTML --> ... |
组件.ts
1 2 3 4 5 6 7 8 9 10 11 | @Component({ ... }) class MyComponent { isDisplayingDetails = false; showDetails() { isDisplayingDetails = true; } } |
查看类绑定和 *ngIf 了解更多信息。
您还可以通过使用条件来简单地使用 angular\\ 的 ngClass 指令。请参阅下面提到的参考 https://angular.io/api/common/NgClass