Avoid changing elements directly through the DOM like *.nativeElement.style.*, since angular is able to render the Templates without a DOM, for instance when using service workers, then these properties may not be available.
Attribute Directives
Change the appearance or behavior of an element, component, or another directive.
They listen to and modify the behavior of other HTML elements, attributes, properties, and components.
Built-in Attribute Directives
Built-in directives use only public APIs.
They do not have special access to any private APIs that other directives can't access.
NgClass
An old way of adding and removing CSS classes in elements.
@Component({
template: `
<!-- Adding 'special' class based on 'isSpecial' value -->
<div [ngClass]="isSpecial ? 'special' : ''">This div is special</div>
<!-- Adding multiple classes with object 'multipleClasses', where each key is the class that will be applied based on its value -->
<div [ngClass]="multipleClass">Div of multiple classes</div>
`
})
export class Component {
protected isSpecial = true;
protected multipleClasses = {
'className1': true,
'className2': false,
}
}
NgStyle
An old way of adding and removing HTML styles in elements.
@Component({
template: `
<!-- Adding single inline style -->
<div [ngStyle]="'font-size': true ? '10px' : '20px'">This div is special</div>
<!-- Adding multiple classes with object 'multipleClasses', where each key is the class that will be applied based on its value -->
<div [ngStyle]="multipleStyles">Div of multiple classes</div>
`
})
export class Component {
protected isSpecial = true;
// You may use regular style names, or camelCase names without quotes
protected multipleStyles = {
'font-weight': true ? 'bold': 'normal',
fontSize: false ? '10px' : '20px',
}
}
NgModel
Use it to display a data property and update that property when the user makes changes. (Adds two-way data binding to HTML form elements)
By default a directive will have a [appDirective] attribute seletor, but it could be a class or component selector as well.
Inject ElementRef to get access to the host DOM element.
@Directive({
standalone: true,
selector: "[appNew]",
})
export class NewDirective {
// Inject the `ElementRef` to get the reference to the Host DOM element
constructor(private el: ElementRef) {
this.el.nativeElement.style.backgroundColor = "yellow";
}
}
<p appNew>This will have yellow background.</p>
Passing values into an attribute directive
Pass values to the Directive with input() using the same selector name as the variable name.
export class NewDirective {
// This uses the same variable name as the directive's selector
appNew = input("yellow");
constructor(private el: ElementRef) {
this.el.nativeElement.style.backgroundColor = this.appNew;
}
}
<p [appNew]="white">This will override the color to white.</p>
Handling user events
You can handle user events or subscribe to event of the DOM with @HostListener().