Attribute Directives

  • Change the appearance or behavior of an element, component, or another directive.

Built-in Attribute Directives

DirectivesDetails

ngClass

Adds or removes a set of CSS classes.

ngStyle

Adds and removes a set of HTML styles.

ngClass

  • with expression

<!-- toggle the "special" class on/off with a property -->
<div [ngClass]="isSpecial ? 'special' : ''">This div is special</div>
  • with method

app.component.ts
currentClasses: Record<string, boolean> = {};
/* . . . */
setCurrentClasses() {
  // CSS classes: added/removed per current state of component properties
  this.currentClasses =  {
    saveable: this.canSave,
    modified: !this.isUnchanged,
    special:  this.isSpecial
  };
}
<div [ngClass]="currentClasses">
    This div is initially saveable, unchanged, and special.
</div>

ngStyle

app.component.ts
currentStyles: Record<string, string> = {};
/* . . . */
setCurrentStyles() {
  // CSS styles: set per current state of component properties
  this.currentStyles = {
    'font-style':  this.canSave      ? 'italic' : 'normal',
    'font-weight': !this.isUnchanged ? 'bold'   : 'normal',
    'font-size':   this.isSpecial    ? '24px'   : '12px'
  };
}
app.component.html
<div [ngStyle]="currentStyles">
  This div is initially italic, normal weight, and extra large (24px).
</div>

Last updated