Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Set CSS Class To Component Variable Value

I'm trying to do something that sounds simple but I'm not finding any examples that meet my needs. I have a simple component that renders an ajax spinner, but I want to allow consumers to pass in a class or multiple classes (seperated by space) as input params to the component and have the components view template add the classes to an img tag in the template. Here is my component:

import { Component, OnInit, Input } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'loading',
    templateUrl: 'loading.html',
    inputs: ['imgClass']

})

export class LoadingComponent {
    @Input() imgClass: string;
}

Here is the view template:

<img [ngClass]="{ imgClass : true}" src="./Content/img/loading_spinner.gif" />

Here is how I want to use it:

 <div class="row" *ngIf="isLoading">
        <div class="col-xs-4"></div>
        <div class="col-xs-4 no-pad"><loading [imgClass]="center-block"></loading></div>
        <div class="col-xs-4"></div>
    </div>

So i want center-block to be added to the img tag through the loading component but It doesn't seem to be working.

When the app loads the markup is this: enter image description here

It's not getting the imgClass variable value it's adding the literal 'imgClass' as the class.

like image 583
cobolstinks Avatar asked Jan 25 '17 20:01

cobolstinks


Video Answer


2 Answers

Change the view template:

<img class="{{imgClass}}" src="./Content/img/loading_spinner.gif" />

This fits better for your needs.

like image 114
dlcardozo Avatar answered Sep 25 '22 19:09

dlcardozo


Just

<img [ngClass]="imgClass"

ngClass supports object, string[], and string as parameter

class="{{...}}" 

caused issues on mobile Safare a while ago, but from what I remember this was fixed in the polyfill.

like image 43
Günter Zöchbauer Avatar answered Sep 22 '22 19:09

Günter Zöchbauer