【问题标题】:Apply default style and onClick change style of a button -Angular 4应用默认样式和 onClick 更改按钮的样式-Angular 4
【发布时间】:2018-06-22 22:34:30
【问题描述】:

我有一个按钮,我想应用按钮的默认样式,当用户单击按钮时,将按钮样式颜色更改为红色,将背景颜色更改为白色。 Blow 是我的 .css 和组件。

.btn-default {
  color: white;
  background-color: blue;

}

.btn-change {
  color: Red;
  background-color: white;
}

组件.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  bntStyle: string;
  AppComponent() {

   this. bntStyle = 'btn-default';
  }
  submit() {
    this.bntStyle = 'btn-change';

  }

.html

<div>
 <button name="Save" [ngClass]="['bntStyle']" (onClick)="submit()">Submit</button>
</div>

【问题讨论】:

    标签: css angular components


    【解决方案1】:

    我知道这对于解决方案来说为时已晚,但这可能对其他人有所帮助。

    .html

    <button [ngClass]="[btnStyle]" (click)="submit()">Submit</button>
    

    .css

    .btn-default {
      color: white;
      background-color: blue;
    }
    
    .btn-change {
      color: Red;
      background-color: white;
    } 
    

    .ts
    (if-else里面的submit函数是切换样式)

    import { Component, VERSION } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    
    export class AppComponent {
     
     btnStyle = 'btn-default';
    
      submit() {
        if(this.btnStyle == 'btn-change') {
          this.btnStyle = 'btn-default';
        } else {
          this.btnStyle = 'btn-change';
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      您正在绑定字符串“btnStyle”。相反,您应该绑定归档:

      <div>
          <button name="Save" [ngClass]="[bntStyle]" (click)="submit()">Submit</button>
      </div>
      

      【讨论】:

      • @Ayala- 我修改了代码 [ngClass]="[bntStyle]" 但它不起作用。
      • 也使用 (click) 而不是 (onClick)
      【解决方案3】:

      将 (OnClick) 更改为 (click),然后使用以下代码 sn-p。

      <div>
       <button name="Save" [ngClass]="[bntStyle]" (click)="submit()">Submit</button>
      </div>
      

      DEMO

      【讨论】:

        猜你喜欢
        • 2013-07-10
        • 2016-01-18
        • 1970-01-01
        • 2012-10-24
        • 1970-01-01
        • 2020-07-02
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多