Attribute Directives

Attribute directives change the appearance or behavior of an element, component, or another directive.

ngClass

Add or remove CSS classes dynamically.

Binding to a single class

<div [class.special]="isSpecial">Content</div>

Binding to multiple classes with an object

<div [ngClass]="{
  'special': isSpecial,
  'active': isActive,
  'disabled': isDisabled
}">
  Content
</div>

Binding to a list of classes

<div [ngClass]="currentClasses">Content</div>
String get currentClasses => isSpecial ? 'special active' : 'active';

ngStyle

Set inline styles dynamically.

Setting a single style

<div [style.color]="isSpecial ? 'red' : 'green'">Styled text</div>
<div [style.font-size.px]="fontSize">Sized text</div>

Setting multiple styles

<div [ngStyle]="{
  'font-weight': isBold ? 'bold' : 'normal',
  'color': textColor,
  'font-size.px': fontSize
}">
  Styled text
</div>

Creating Custom Attribute Directives

Create a custom directive by annotating a class with @Directive:

import 'package:angulardart/angular.dart';

@Directive(
  selector: '[highlight]',
)
class HighlightDirective {
  final HtmlElement _el;

  HighlightDirective(this._el);

  @HostListener('mouseenter')
  void onMouseEnter() {
    _el.style.backgroundColor = 'yellow';
  }

  @HostListener('mouseleave')
  void onMouseLeave() {
    _el.style.backgroundColor = '';
  }
}

Passing values to directives

Use @Input() to accept values:

@Directive(
  selector: '[highlight]',
)
class HighlightDirective {
  final HtmlElement _el;

  @Input()
  String highlight = 'yellow';

  HighlightDirective(this._el);

  @HostListener('mouseenter')
  void onMouseEnter() {
    _el.style.backgroundColor = highlight;
  }

  @HostListener('mouseleave')
  void onMouseLeave() {
    _el.style.backgroundColor = '';
  }
}

Usage:

<p highlight="lightblue">Highlight me in blue!</p>
<p [highlight]="highlightColor">Dynamic color</p>

Responding to user actions

@Directive(
  selector: '[tooltip]',
)
class TooltipDirective {
  final HtmlElement _el;
  HtmlElement? _tooltip;

  @Input()
  String tooltip = '';

  TooltipDirective(this._el);

  @HostListener('mouseenter')
  void onMouseEnter() {
    _tooltip = DivElement()
      ..text = tooltip
      ..style.position = 'absolute'
      ..style.backgroundColor = '#333'
      ..style.color = '#fff'
      ..style.padding = '4px 8px'
      ..style.borderRadius = '4px';
    _el.append(_tooltip!);
  }

  @HostListener('mouseleave')
  void onMouseLeave() {
    _tooltip?.remove();
    _tooltip = null;
  }
}

Directive Lifecycle

Directives have the same lifecycle hooks as components:

  • ngOnInit - After inputs are set
  • ngOnDestroy - Before the directive is destroyed
  • ngOnChanges - When input bindings change
@Directive(selector: '[myDirective]')
class MyDirective implements OnInit, OnDestroy {
  @override
  void ngOnInit() {
    print('Directive initialized');
  }

  @override
  void ngOnDestroy() {
    print('Directive destroyed');
  }
}