Neoheurist
Neoheurist

Reputation: 3484

How can I get the classes applied via HTML on an Angular 2 component?

I want to use a component that I've created as follows:

<vx-alert class="au-upper-center">
    <p>Upper Center</p>
</vx-alert>

Within the vx-alert component I want to pull the list of classes that were applied in the HTML that caused the component to be instantiated. Ultimately I want to either append additional classes to the vx-alert component. I am able to replace the vx-alert component classes very easily (as follows):

@Component({
    moduleId: module.id,
    selector: 'vx-alert',
    templateUrl: 'alert.html'
})
export class AlertComponent extends I18N implements OnInit {
    @HostBinding('class') private classList:string;

    ngOnInit() {
        this.classList = 'au-ease-in-out au-20000ms';
   }
}

but when this.classList is assigned as new value, the original class(es) set within the HTML code are overwritten... so how can I retrieve the HTML provided classes so that I can concatenate these to my programmatically determined classes?

My Plunker has been updated to use the answer provided by @acdcjunior:

http://embed.plnkr.co/AKYU9ANRm5ogzhlzY9G0/

Upvotes: 1

Views: 133

Answers (1)

acdcjunior
acdcjunior

Reputation: 135872

You could consider the class attribute of vx-alert an input to it (@Input('class')). That way, you can read its value.

After that, you can use @HostBinding('class') to amend it:

@Component({
    moduleId: module.id,
    selector: 'vx-alert',
    templateUrl: 'alert.html'
})
export class AlertComponent extends I18N implements OnInit {
  @Input('class') initialClassList: string;
  @HostBinding('class') private classList:string;

  ngOnInit() {
    this.classList = this.initialClassList + ' au-ease-in-out au-20000ms';
  }
}

See demo plunker here.

Upvotes: 2

Related Questions