Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use NgClass with a custom Pipe

Tags:

angular

I'm trying to assign a custom class on a span based on a result given from a pipe trasform. Sadly, I'm not getting it to work.

Here's the scenario. I'm itering this object in a ngFor statement:

"documents": [
  {
    "document_ext": "pdf"
  } ,
  {
    "document_ext": "doc"
  }
]

While itering I want to assign a custom class based on the document_ext. but this is causing me following error:

Error: Got interpolation ({{}}) where expression was expected at column 0 in [{{doc?.document_ext | documentaleType}}]

The html code:

<ng-container *ngFor="let doc of documentList">
  <div class="row">
    <div class="doc-type">
      <span class="row-icon" [ngClass]="{{doc?.document_ext | documentaleType}}"> 
      </span>
     </div>
  </div>
</ng-container>

And the simple pipe just return a standard value for now:

export class DocumentaleTypePipe {
    transform(ext: string): string {
        return "p3-018-dummy";
    }
} 

I don't want to call a function, that's why I've choose to use a pipe. What am I missing?

Any help is appreciated.

EDIT

Solved this way:

<span class="row-icon" [ngClass]="[doc.document_ext ? (doc.document_ext | documentaleType) : 'p3-018-dummy']"></span>
like image 637
Jacopo Sciampi Avatar asked Sep 15 '25 09:09

Jacopo Sciampi


1 Answers

PIPE

@Pipe({
  name: 'getClass'
})
export class GetClassPipe implements PipeTransform {
  transform(obj: any, args?: any): any {
    return obj['document_ext'];
  }
}

COMPONENT

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public documents = [
    {
      "document_ext": "pdf"
    },
    {
      "document_ext": "doc"
    }
  ]
}

HTML

<div *ngFor="let doc of documents" [ngClass]="doc | getClass">test</div>

CSS

.pdf {
  color:red
}

.doc {
  color:green
}

Here's a live demo https://stackblitz.com/edit/use-ngclass-with-a-custom-pipe

like image 184
maxime1992 Avatar answered Sep 17 '25 23:09

maxime1992