如何默认将 class 设置为数组中的第一个项目并将其删除并在单击时应用于另一个项目?
How can I set a class to the first Item in array by default and remove it and apply to another item on click?
在 Angular 中,您可以像这样使用 ngClass 有条件地应用您的 class。
<div
*ngFor="let group of step.groups; let firstItem = first;"
class="layout--stepper__subgroup"
ngClass]="{'is-active': group.prop === activeProp}"
(click)="scrollToSection(group)">
p class="t-data">{{group.header}}</p>
</div>
scrollToSection(group) {
this.activeProp = group.prop;
let scroll = document.querySelector(`#${group.prop}`).scrollIntoView();
}
现在,每当我单击列表中的项目时,class is-active
将应用于该特定列表项目。但是,如果我想默认将 is-active
应用于列表中的第一项怎么办?
如果我将代码更改为:
ngClass]="{'is-active': group.prop === activeProp || firstItem}"
现在列表中的第一个项目和单击的项目都会有 is-active
class。如何将列表中的第一项设置为默认具有 is-active
class,然后在单击列表中的另一项时将其删除?
将activeProp初始化为groups数组第一组的prop:
if(this.step.groups.length > 0)
this.activeProp = this.step.groups[0].prop;
你的第一个条件:
[ngClass]="{'is-active': group.prop === activeProp}"
会运行顺利
如果您知道 firstItem
的 prop
值,最简单的方法是将 activeProp
初始设置为该值。
如果您不知道该值,请仅在未定义 activeProp
时尝试将 is-active
设置为您的 firstItem
,即未选择任何项目时。
[ngClass]="{'is-active': group.prop === activeProp || (firstItem && !activeProp)}"
在 Angular 中,您可以像这样使用 ngClass 有条件地应用您的 class。
<div
*ngFor="let group of step.groups; let firstItem = first;"
class="layout--stepper__subgroup"
ngClass]="{'is-active': group.prop === activeProp}"
(click)="scrollToSection(group)">
p class="t-data">{{group.header}}</p>
</div>
scrollToSection(group) {
this.activeProp = group.prop;
let scroll = document.querySelector(`#${group.prop}`).scrollIntoView();
}
现在,每当我单击列表中的项目时,class is-active
将应用于该特定列表项目。但是,如果我想默认将 is-active
应用于列表中的第一项怎么办?
如果我将代码更改为:
ngClass]="{'is-active': group.prop === activeProp || firstItem}"
现在列表中的第一个项目和单击的项目都会有 is-active
class。如何将列表中的第一项设置为默认具有 is-active
class,然后在单击列表中的另一项时将其删除?
将activeProp初始化为groups数组第一组的prop:
if(this.step.groups.length > 0)
this.activeProp = this.step.groups[0].prop;
你的第一个条件:
[ngClass]="{'is-active': group.prop === activeProp}"
会运行顺利
如果您知道 firstItem
的 prop
值,最简单的方法是将 activeProp
初始设置为该值。
如果您不知道该值,请仅在未定义 activeProp
时尝试将 is-active
设置为您的 firstItem
,即未选择任何项目时。
[ngClass]="{'is-active': group.prop === activeProp || (firstItem && !activeProp)}"