Angular Directives

Level : Beginner
Mentor: Shailendra Chauhan
Duration : 00:03:30

NgClass

NgClass allows you to dynamically add or remove CSS classes to/from HTML elements based on specific conditions.

Example

<div [ngClass]="isSpecial ? 'special-class' : 'normal-class'">Dynamic Class Example</div>

NgStyle

NgStyle enables you to apply dynamic inline styles to HTML elements based on certain conditions.

Example

<p [ngStyle]="{'font-size': isLargeFont ? '20px' : '14px', 'color': textColor}">Dynamic Styling</p>

NgModel

NgModel provides two-way data binding for form controls, allowing data synchronization between the component and the view.

Example

<input [(ngModel)]="username" placeholder="Enter your name">

NgIf Directive

NgIf is used for conditional rendering, where the associated element is displayed or removed based on a given condition.

Example

<div *ngIf="showElement">This div will only appear if showElement is true</div>

NgFor Directive

NgFor is used to iterate over arrays or collections to generate multiple instances of an element.

Example

<ul>
  <li *ngFor="let item of items">{{ item.name }}</li>
</ul>

NgSwitch Directive

NgSwitch is used to conditionally display different content based on a given value or expression.

Example

<div [ngSwitch]="choice">
  <p *ngSwitchCase="'A'">Option A is selected</p>
  <p *ngSwitchCase="'B'">Option B is selected</p>
  <p *ngSwitchDefault>Default option</p>
</div>

NgSwitchCase Directive

NgSwitchCase is used within an NgSwitch block to define different cases for the switch condition.

Example

<div [ngSwitch]="selectedOption">
  <p *ngSwitchCase="'red'">Red option selected</p>
  <p *ngSwitchCase="'blue'">Blue option selected</p>
</div>

NgSwitchDefault Directive

NgSwitchDefault is used within an NgSwitch block to define the default case when no other cases match.

Example

<div [ngSwitch]="selectedOption">
  <p *ngSwitchCase="'red'">Red option selected</p>
  <p *ngSwitchDefault>Default option selected</p>
</div>
Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this