ngclass单击时更改颜色

时间:2020-04-12 04:30:47

标签: angular typescript

我正在尝试添加收藏夹,单击时它应该更改颜色,但是仅当我重新加载页面时它才更改颜色。单击时无需重新加载页面,我需要对其进行更改。这是我的代码和演示Stackblitz

HTML

<mat-icon *ngIf="conference.favourite === true" [ngClass]="{'true' : conference.favourite === true?'true' :  flag === true? true:false}"  (click)="unfavour(conference.conferenceId)">favorite</mat-icon>
<mat-icon *ngIf="conference.favourite === false" [ngClass]="{'false' : conference.favourite === false?'false' :  flag === false? false:true}"  (click)="passFavor(conference.conferenceId)">favorite</mat-icon>

组件

public flag: boolean = false;

GetFavourite(event){
    const userid = this.service.getUserId();
    console.log(userid, event)

      let requestData = {
        userId:userid,
        conferenceId:event,
        favourite:true
      }
      return this.http.favourite(requestData).subscribe(res =>{
        this.flag = this._conference['favourite'];
        console.log(this._conference['favourite']);
      })

  }

unfavourite(event){
    const userid = this.service.getUserId();
    let requestData = {
      userId:userid,
      conferenceId:event,
      favourite:false
    }
    return this.http.favourite(requestData).subscribe(res =>{
      this.flag = this._conference['favourite'];
      console.log(this._conference['favourite']);
    })
  }

CSS

.true{
    color: #FF4040;
}
.false{
    color: #000;
}

2 个答案:

答案 0 :(得分:3)

使用ngClass条件使代码清晰可见,例如:

<?php

namespace ACX\inc;

use ACX\lib\Api; // This needs to be imported

class SC {

    // other code

    public static function getDataSets(){
        $data = Api::getDataJSON(); // You're calling Api.php class here
        return $data;
    }

    // other code
}

并修改与每个选项关联的[ngClass]="hero.fav ? 'primary' : 'secondary'" 属性,因此无需维护一个局部变量即可切换点击或类别。

HTML:

hero.fav

CSS:

<ul>
  <li *ngFor="let hero of heroes" (click)="test(hero.fav = !hero.fav)">
    <div [ngClass]="hero.fav ? 'primary' : 'secondary'" (click)="test(hero.id)">{{ hero.name }}</div>
  </li>
</ul>

Working_Demo

答案 1 :(得分:1)

添加了一些括号,但条件可能不正确

<mat-icon *ngIf="conference.favourite === true" [ngClass]="{'true' : (conference.favourite === true)? true :  (flag === true) ? true:false}"  (click)="unfavour(conference.conferenceId)">favorite</mat-icon>
<mat-icon *ngIf="conference.favourite === false" [ngClass]="{'false' : (conference.favourite === false) ? false :  (flag === false)? false:true}"  (click)="passFavor(conference.conferenceId)">favorite</mat-icon>