【发布时间】:2020-07-06 18:16:03
【问题描述】:
我正在尝试将 css 类动态添加到 Angular 9 中的按钮。我根据布尔值有条件地添加一个或另一个类。我还有一个点击事件可以切换相同的布尔值。我遇到的问题是,当页面加载时,既不 css 类被应用。只有在单击按钮后才会应用一个类或另一个类,然后,css 类会按预期切换。我已经搜索过类似的问题,但找不到任何与我的问题足够相似的问题来帮助我找到解决方案。我还搜索并阅读了几次如何使用 ngClass。因为看起来我想做的事情应该非常简单,我猜我错过了一些明显的东西。这是sn-ps的代码:
delivery-schedule.component.html:
<div>
<app-date-button></app-date-button>
</div>
日期按钮.component.html
<button
class="btn-date"
(click)="toggleSelected()"
[ngClass]="[isSelected ? 'selected' : 'unselected']">
<div class="day">Fri</div>
<div>Jan 1</div>
</button>
date-button.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-date-button',
templateUrl: './date-button.component.html',
styleUrls: ['./date-button.component.sass']
})
export class DateButtonComponent implements OnInit {
constructor() { }
isSelected: boolean = false;
toggleSelected() {
this.isSelected = !this.isSelected;
}
ngOnInit() {
}
}
当我的应用加载时,我得到class="btn-date",但点击按钮后,我得到class="btn-date selected"。
我希望最初得到class="btn-date unselected"。任何指导将不胜感激。谢谢!
【问题讨论】:
-
在 Angular 引导期间您是否检查过没有任何其他运行时错误(与您的问题没有关联)?
-
我将您的代码放入堆栈闪电战中,它可以按照您想要的方式运行。可能还有其他错误。 stackblitz.com/edit/…