Skip to content

Provide a way to bind class at runtime in template #2927

Closed

Description

@coldume

Angular2 currently provide a way to bind css class as [class.fa-train]="true", it is great if you can also bind them at runtime, something like [class:variable]="true" or simply [class:variable].

Here is a simple example,

this.icons = ['fa-train', 'fa-subway', 'fa-bed']
<i *ng-for="#icon of icons" class="fa" [class:icon]="true"></i>
<!--output-->
<i class="fa fa-train"></i>
<i class="fa fa-subway"></i>
<i class="fa fa-bed"></i>

Here is an example with bootstrap and form. Before:

<div class="form-group" [class.has-success]="form.controls.name.valid && !database.duplicate" [class.has-warning]="form.controls.name.valid && database.duplicate" [class.has-error]="!form.controls.name.valid">
  <input type="text" class="form-control" placeholder="Your name">
</div>

After:

<div class="form-group" [class:nameValidity]="true">
  <input type="text" class="form-control" placeholder="You name">
</div>
get nameValidity () {
  if (this.form.controls.name.valid && !this.database.duplicate) return 'has-success';
  if (this.form.controls.name.valid && this.database.duplicate) return 'has-warning'
  if (!this.form.controls.name.valid) return 'has-error';
}

Thanks!

Activity

  1. matanlurey commented on Jul 8, 2015

    @matanlurey
    Contributor

    You should be able to use [class] from #2664. In your example:

    <i *ng-for="#icon of icons" [class]="icon"></i>
  2. coldume commented on Jul 8, 2015

    @coldume
    Author

    Thanks, this is exactly what I want!

  3. angular-automatic-lock-bot commented on Sep 6, 2019

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  4. locked and limited conversation to collaborators on Sep 6, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions