我通过ngfor指令创建了几个div。
<div class="card" *ngFor="let item of list" [ngClass]="{'is-collapsed': isCollapsed , 'is-expanded':!isCollapsed}" (click)="toggle()">
<div class="card__inner " [ngClass]="{'js-expander': isCollapsed}">
<span>Card</span>
<mat-icon class="fa fa-folder-o">folder</mat-icon>
</div>
<div class="card__expander">
<mat-icon class="fa fa-close" [ngClass]="{'js-collapser': isCollapsed}" >close</mat-icon>
Expander
</div>
</div>
现在,如果我单击切换功能,它应该仅扩展特定的div。但是它扩展了所有的div。如何解决? 这是我的切换功能:
isCollapsed: boolean;
list = [{a:1},{a:1},{a:1}]
constructor() { }
ngOnInit() {
this.isloading = true;
this.isCollapsed = true;
}
toggleIsCollapsed() {
this.isCollapsed = !this.isCollapsed;
}
我如何引用将基于点击扩展的特定内容?我应该怎么做?
答案 0 :(得分:1)
尝试这样:
<div class="card" *ngFor="let item of list; let i=index"
[ngClass]="{'is-collapsed': item.isCollapsed , 'is-expanded':!isCollapsed}"
(click)="item.isCollapsed = !item.isCollapsed ">
<div class="card__inner " [ngClass]="{'js-expander': item.isCollapsed}">
<span>Card</span>
<mat-icon class="fa fa-folder-o">folder</mat-icon>
</div>
<div class="card__expander">
<mat-icon class="fa fa-close" [ngClass]="{'js-collapser': item.isCollapsed}">close</mat-icon>
Expander
</div>
</div>
答案 1 :(得分:1)
为什么不编写指令来切换元素上的类?然后,您可以在传递类作为输入的整个过程中重用它。
import {Directive, ElementRef, Input} from '@angular/core';
@Directive({
selector: '[toggle-class]',
host: {
'(click)': "toggleClass()"
}
})
export class ToggleClassDirective {
@Input() toggle_class: string = 'is-collapsed';
private el:ElementRef;
constructor(el: ElementRef) {
this.el = el;
}
toggleClass() {
this.el.nativeElement.classList.toggle(this.toggle_class);
}
}
然后在您的HTML中
<div class="card" toggle-class toggle_class="is-collapsed"></div>