代码之家  ›  专栏  ›  技术社区  ›  Nxt3

无法使用异步管道动态应用CSS名称

  •  0
  • Nxt3  · 技术社区  · 6 年前

    我有这样一个组件:

    import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
    import { Observable } from 'rxjs';
    
    import { Job } from '../models';
    import { PipelineJobsQuery, PipelineSelectQuery } from '../queries';
    import { PipelineJobsService } from '../services';
    
    @Component({
      selector: 'pi-pipeline-jobs',
      templateUrl: './pipeline-jobs.component.html',
      styleUrls: ['./pipeline-jobs.component.scss'],
      changeDetection: ChangeDetectionStrategy.OnPush
    })
    export class PipelineJobsComponent implements OnInit {
      public pipelineName: string;
      public pipelineJobs$: Observable<Job[]>;
    
      constructor(
        private readonly pipelineJobsQuery: PipelineJobsQuery,
        private readonly pipelineJobsService: PipelineJobsService,
        private readonly pipelineSelectQuery: PipelineSelectQuery
      ) {}
    
      public getJobStatus(job: Job): string {
        const status: string = job.next_build
          ? job.next_build.status
          : job.finished_build
            ? job.finished_build.status
            : 'no-build-status';
    
        console.log(job, status);
        return status;
      }
    
      public ngOnInit() {
        // Reload the pipelineJobs when the selectedPipeline changes
        this.pipelineSelectQuery.selectedPipeline$.subscribe(pipeline => {
          this.pipelineJobsService.getPipelineJobs(pipeline);
          this.pipelineJobs$ = this.pipelineJobsQuery.pipelineJobs;
          this.pipelineName = pipeline;
        });
      }
    }
    

    <mat-card *ngFor="let job of (pipelineJobs$ | async)"
              class="job-card job-card-{{ getJobStatus(job) }}">
        {{job.name}} - <strong>{{getJobStatus(job)}}</strong>
    </mat-card>
    

    .job-card {
      margin: 8px;
    }
    
    .job-card-succeeded {
      background-color: green;
    }
    

    如果我这样应用类名,那么模板不会呈现 mat-card 元素作为卡片。我知道当时数据就在那里 getJobStatus() 函数被调用,所以我不确定为什么它会破坏卡片的CSS。应该是这样的:

    enter image description here


    结果是这样的:

    enter image description here

    1 回复  |  直到 6 年前
        1
  •  1
  •   G. Tranter    6 年前

    因为你和 class 您正在重写应用于的所有类 mat-card 通过组件本身-特别是 mat卡 ,而不是使用 ngClass 是为了这个目的- 添加 类而不是 课程:

    <mat-card *ngFor="let job of (pipelineJobs$ | async)"
            [ngClass]="'job-card job-card-' + getJobStatus(job)">
        {{job.name}} - <strong>{{getJobStatus(job)}}</strong>
    </mat-card>