Built-in

Attribute directives listen to and modify the behavior of other HTML elements, attributes, properties, and components.

The most common attribute directives are as follows:

Common directivesDetails

Adds and removes a set of CSS classes.

Adds and removes a set of HTML styles.

Adds two-way data binding to an HTML form element.

NgClass

1. Using ngClass with a Simple Condition

Suppose you have a component and you want to toggle a CSS class based on a boolean condition.

HTML:

<div [ngClass]="{ 'highlight': isHighlighted }">
  This div is highlighted based on the condition.
</div>

Component (TypeScript):

import { Component } from '@angular/core';

@Component({
  selector: 'app-highlight-example',
  templateUrl: './highlight-example.component.html',
  styleUrls: ['./highlight-example.component.css']
})
export class HighlightExampleComponent {
  isHighlighted: boolean = true; // Change to false to see the difference
}

CSS:

.highlight {
  background-color: yellow;
}

Result:

If isHighlighted is true, the div will have a yellow background due to the highlight class being applied:

<div class="highlight">
  This div is highlighted based on the condition.
</div>

If isHighlighted is false, the div will have no special styling applied and will appear as default.

2. Using ngClass with Multiple Conditions

You can apply multiple CSS classes based on different conditions.

HTML:

<div [ngClass]="{
    'highlight': isHighlighted,
    'bold': isBold,
    'italic': isItalic
}">
  This div's classes are dynamically applied.
</div>

Component (TypeScript):

import { Component } from '@angular/core';

@Component({
  selector: 'app-multi-condition-example',
  templateUrl: './multi-condition-example.component.html',
  styleUrls: ['./multi-condition-example.component.css']
})
export class MultiConditionExampleComponent {
  isHighlighted: boolean = true;
  isBold: boolean = false;
  isItalic: boolean = true;
}

CSS:

.highlight {
  background-color: yellow;
}

.bold {
  font-weight: bold;
}

.italic {
  font-style: italic;
}

Result:

The div will have a yellow background (due to highlight), and italic text (due to italic). It will not be bold because isBold is false:

<div class="highlight italic">
  This div's classes are dynamically applied.
</div>

3. Using ngClass with an Array of Classes

If you want to apply a list of classes based on a condition, you can use an array.

HTML:

<div [ngClass]="getClasses()">
  This div's classes are applied from an array.
</div>

Component (TypeScript):

import { Component } from '@angular/core';

@Component({
  selector: 'app-array-class-example',
  templateUrl: './array-class-example.component.html',
  styleUrls: ['./array-class-example.component.css']
})
export class ArrayClassExampleComponent {
  isHighlighted: boolean = true;
  isBold: boolean = false;

  getClasses() {
    return {
      'highlight': this.isHighlighted,
      'bold': this.isBold
    };
  }
}

CSS:

.highlight {
  background-color: yellow;
}

.bold {
  font-weight: bold;
}

Result:

The div will have a yellow background due to highlight being true. It will not be bold because isBold is false:

<div class="highlight">
  This div's classes are applied from an array.
</div>

4. Using ngClass with an Object

You can apply CSS classes based on an object defined in the component.

HTML:

<div [ngClass]="classObject">
  This div's classes are applied from an object.
</div>

Component (TypeScript):

import { Component } from '@angular/core';

@Component({
  selector: 'app-object-class-example',
  templateUrl: './object-class-example.component.html',
  styleUrls: ['./object-class-example.component.css']
})
export class ObjectClassExampleComponent {
  isHighlighted: boolean = true;
  isBold: boolean = false;

  classObject = {
    'highlight': this.isHighlighted,
    'bold': this.isBold
  };
}

CSS:

.highlight {
  background-color: yellow;
}

.bold {
  font-weight: bold;
}

Result:

The div will have a yellow background due to highlight being true. It will not be bold because isBold is false:

<div class="highlight">
  This div's classes are applied from an object.
</div>

5. Combining ngClass with ngStyle

You can combine ngClass with ngStyle to apply both CSS classes and dynamic styles.

HTML:

<div [ngClass]="{ 'highlight': isHighlighted }" [ngStyle]="{ 'font-size': fontSize }">
  This div's classes and styles are dynamically applied.
</div>

Component (TypeScript):

import { Component } from '@angular/core';

@Component({
  selector: 'app-class-style-example',
  templateUrl: './class-style-example.component.html',
  styleUrls: ['./class-style-example.component.css']
})
export class ClassStyleExampleComponent {
  isHighlighted: boolean = true;
  fontSize: string = '20px'; // Change font size if needed
}

CSS:

.highlight {
  background-color: yellow;
}

Result:

The div will have a yellow background due to highlight being true and will have a font size of 20px:

<div class="highlight" style="font-size: 20px;">
  This div's classes and styles are dynamically applied.
</div>

Summary

  • ngClass is a powerful Angular directive for dynamically applying CSS classes based on conditions.

  • Usage options include: objects with conditions, arrays of classes, and methods returning class objects.

  • Combining with ngStyle allows for dynamic styling along with class application.

NgStyle

Scenario:

Let's say you have a component where you want to dynamically change the background color, font size, and text color of a div based on certain conditions or user input.

1. Component TypeScript:

Create a component that defines the dynamic styles.

TypeScript (Component):

typescriptCopy codeimport { Component } from '@angular/core';

@Component({
  selector: 'app-style-example',
  templateUrl: './style-example.component.html',
  styleUrls: ['./style-example.component.css']
})
export class StyleExampleComponent {
  // Define variables for dynamic styling
  isHighlighted: boolean = true;
  fontSize: string = '20px';
  backgroundColor: string = 'lightblue';
  textColor: string = 'darkblue';

  // Method to return styles as an object
  getDynamicStyles() {
    return {
      'background-color': this.backgroundColor,
      'font-size': this.fontSize,
      'color': this.textColor
    };
  }
}

2. Component HTML:

Use ngStyle to apply dynamic styles to the div.

HTML:

htmlCopy code<div [ngStyle]="getDynamicStyles()">
  This div's styles are dynamically applied based on component properties.
</div>

<!-- Buttons to change the styles dynamically -->
<button (click)="isHighlighted = !isHighlighted">Toggle Highlight</button>
<button (click)="fontSize = '30px'">Increase Font Size</button>
<button (click)="fontSize = '15px'">Decrease Font Size</button>
<button (click)="backgroundColor = 'lightgreen'">Change Background Color</button>
<button (click)="textColor = 'red'">Change Text Color</button>

3. Component CSS (Optional):

You may have some CSS styles if needed, but in this case, they are not strictly necessary.

CSS:

/* style-example.component.css */
/* No additional styles needed for this example */

Result:

  • The div will have its background color, font size, and text color dynamically set according to the values defined in the component.

  • Clicking the buttons will update the properties (fontSize, backgroundColor, textColor) and, in turn, update the inline styles of the div accordingly.

Rendered HTML:

Initially, the div will look like this:

<div style="background-color: lightblue; font-size: 20px; color: darkblue;">
  This div's styles are dynamically applied based on component properties.
</div>

After Interactions:

  • Clicking "Toggle Highlight" will toggle the isHighlighted flag (though it's not directly used here, you could incorporate it in the style changes).

  • Clicking "Increase Font Size" will set the fontSize to 30px.

  • Clicking "Decrease Font Size" will set the fontSize to 15px.

  • Clicking "Change Background Color" will change the backgroundColor to lightgreen.

  • Clicking "Change Text Color" will change the textColor to red.

As a result of these interactions, the styles applied to the div will dynamically update based on the properties and methods defined in the component.

Example after button clicks:

<div style="background-color: lightgreen; font-size: 30px; color: red;">
  This div's styles are dynamically applied based on component properties.
</div>

Summary

  • ngStyle is used to apply dynamic inline styles to HTML elements based on component properties or methods.

  • Dynamic Styles can be adjusted interactively or based on any logic within your component, providing a flexible way to manage inline styles.

NgModel

Scenario:

Let's create a component where you use ngModel to bind an input field to a component property. We will also include a button to update the component property, and this change will automatically reflect in the input field.

1. Component TypeScript:

Define the properties and methods for binding and updating in the component.

TypeScript (Component):

typescriptCopy codeimport { Component } from '@angular/core';

@Component({
  selector: 'app-ngmodel-example',
  templateUrl: './ngmodel-example.component.html',
  styleUrls: ['./ngmodel-example.component.css']
})
export class NgModelExampleComponent {
  // Define a property to bind to
  userName: string = 'John Doe';

  // Method to update the userName
  updateName(newName: string) {
    this.userName = newName;
  }
}

2. Component HTML:

Use ngModel to bind an input field to the userName property. Include a button to update the userName.

HTML:

htmlCopy code<!-- Input field bound to userName with ngModel -->
<input [(ngModel)]="userName" placeholder="Enter your name" />

<!-- Display the userName below the input -->
<p>Your name is: {{ userName }}</p>

<!-- Button to update the userName property -->
<button (click)="updateName('Alice')">Change Name to Alice</button>
<button (click)="updateName('Bob')">Change Name to Bob</button>

3. Component CSS (Optional):

You may include some CSS for styling, but it’s not essential for this example.

CSS:

cssCopy code/* ngmodel-example.component.css */
input {
  margin: 10px;
  padding: 5px;
  font-size: 16px;
}

p {
  font-size: 18px;
  color: #333;
}

button {
  margin: 5px;
  padding: 10px;
  font-size: 16px;
}

Result:

  • Initial State: The input field will be pre-filled with the value 'John Doe', and the paragraph below will display 'Your name is: John Doe'.

Rendered HTML:

Initially:

htmlCopy code<input value="John Doe" placeholder="Enter your name" />
<p>Your name is: John Doe</p>
<button>Change Name to Alice</button>
<button>Change Name to Bob</button>
  • User Interaction: Typing in the input field will immediately update the userName property in the component and vice versa.

  • Button Clicks: Clicking "Change Name to Alice" or "Change Name to Bob" will update the userName property and automatically reflect the changes in both the input field and the paragraph.

After Interaction:

For example, after clicking "Change Name to Alice":

<input value="Alice" placeholder="Enter your name" />
<p>Your name is: Alice</p>
<button>Change Name to Alice</button>
<button>Change Name to Bob</button>

Summary

  • ngModel creates a two-way data binding between the input field and the component property.

  • Changes in the input field automatically update the component property and vice versa.

  • User interactions with input fields and buttons show how ngModel synchronizes the view and model seamlessly.

Last updated