Tuesday, 26 November 2019

Angular Template Syntax and NgClass & NgStyle Directives

<!-- Native Class and Style Attributes -->
<input class="is-danger my-button" style="border: none; color: blue">
<!-- Angular class and style Bindings -->
<input [class.is-danger]="booleanProp" [style.border]="borderProp">
<!-- ngClass -->
<input [ngClass]="{'is-danger': booleanProp, 'myButton': true}">
<input [ngClass]="isDangerButton">
<!-- ngStyle -->
<input [ngStyle]="{'border': borderProp, 'color': colorProp}">
<input [ngStyle]="hasColorBorder">
<!--
booleanProp, borderProp, etc...
would be properties from our
Typescript class
-->

NgClass



NgClass can receive input via inline declarations, or a property/method from our TypeScript class. This can make the syntax feel more convoluted than it really is. Ultimately, NgClass can take the following as input:
  • A space-delimited String [ngClass]="is-info is-item has-border"
  • An Array of Strings [ngClass]="['is-info', 'is-item', 'has-border'"]
  • An Object [ngClass]="{'is-info': true, 'is-item': true}
All of the above examples are inline and could be replaced with a Typescript property/method as long as the expression returns valid input:
export class MyComponentClass {
myStringProperty = "is-info is-item has-border";
myArrayProperty = ['is-info', 'is-item', 'has-border'];
myObjectProperty = {'is-info': true, 'is-item': true};
}
  • [ngClass]="myStringProperty"
  • [ngClass]="myArrayProperty"
  • [ngClass]="myObjectProperty"


Key Points

  • We can pass a Typescript property/method or write an expression inline to our NgClass Directive
  • NgClass can take a String, Array of Strings, or Object Expression as input.
  • Under the hood, NgClass is adding/removing classes via Renderer2 addClass() and removeClass()
  • NgClass appends, it does not overwrite.



NgStyle

NgClass and NgStyle share a significant amount of functionality and behavior. The key difference is:
  • NgStyle takes a key-value pair object as input.
  • NgStyle applies styles and not classes.
  • NgStyle will overwrite styles defined by the native style attribute.

Syntax

NgStyle takes a key-value pair object, where the key is a CSS style. An optional suffix can be added to the key, making keys such as this viable:
[ngStyle]="{font-size.px: 16}" Instead of [ngStyle]="{font-size: 16px}"
Similar to NgClass, NgStyle can be passed input inline or use a Typescript property/method[ngStyle]="myObjectExpressionProperty"

Key Takeaways

  • NgStyle can accept a key-value pair as input, where the key is a valid CSS Style
  • NgStyle can be passed input via inline or a Typescript property or method
  • NgStyle under the hood utilizes Angular’s Renderer2 to invoke setStyle() and removeStyle()
  • NgStyle will overwrite existing styles on the element.

No comments:

Post a Comment