【问题标题】:ngClass not applying css classes initially, only after clickngClass 最初不应用 css 类,仅在单击后
【发布时间】: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/…

标签: angular ng-class


【解决方案1】:

编辑:

由于@cjd82187 提供的StackBlitz 可以很好地与您的代码配合使用,因此您的代码中的其他地方可能存在一些错误(例如,检查浏览器的开发者控制台)。

旧答案:

尝试将您的ngOnInit 更改为:

isSelected: boolean;

...

ngOnInit() {
  this.isSelected = false;
}

或者实现AfterViewInit:

一个生命周期钩子,在 Angular 完全初始化一个 组件的视图。

export class DateButtonComponent implements OnInit, AfterViewInit {

  isSelected: boolean;

  ...

  ngAfterViewInit() {
    this.isSelected = false;
  }
}

【讨论】:

  • 我尝试了这两个建议,但不幸的是我仍然看到与以前相同的行为。
  • 嗯。你能提供一个演示/StackBlitz 吗?
猜你喜欢
  • 1970-01-01
  • 2023-03-17
  • 2019-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-17
  • 1970-01-01
  • 2017-11-16
相关资源
最近更新 更多