Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • AngularJS Tutorial
  • AngularJS Directives
  • AngularJS Functions
  • AngularJS Filters
  • AngularJS Examples
  • AngularJS Interview Questions
  • Angular ngx Bootstrap
  • AngularJS Cheat Sheet
  • AngularJS PrimeNG
  • JavaScript
  • Web Technology
Open In App
Next Article:
Built-in directives in Angular
Next article icon

Built-in directives in Angular

Last Updated : 28 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Directives are markers in the Document Object Model(DOM). Directives can be used with any controller or HTML tag which will tell the compiler what exact operation or behavior is expected. There are some directives present that are predefined but if a developer wants he can create new directives (custom-directive).

There are basically 3 types of directives and each type has some built-in directives. In this article, we will discuss all 3 types of directives and their built-in directives.

Table of Content

  • 1. Component Directives
  • 2. Attribute Directives
  • 3. Structural Directives

1. Component Directives

Components are directives with templates. They are the building blocks of Angular applications, encapsulating both the UI (User Interface) and the behavior of a part of the application. Components are used to create reusable and modular UI elements. They are declared using the @Component decorator and typically have a corresponding HTML template.

Syntax: In the component below, we have used the @Component here to define a component.

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

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {}

2. Attribute Directives

Attribute directives are used to change the appearance or behavior of a DOM element by applying custom attributes. These directives are applied to elements as attributes and are denoted by square brackets. Attribute directives are often used for tasks such as dynamic styling, input validation, or DOM manipulation.

Built-in Attribute Directives:

1. ngClass: The NgClass directive allows us to conditionally apply CSS classes to HTML elements.

Syntax:

<div [ngClass]="{'class-name': condition}">
<!-- Content here -->
</div>

2. ngStyle: The NgStyle directive enables you to conditionally apply inline styles to HTML elements.

Syntax:

<div [ngStyle]="{'property': 'value'}">
<!-- Content here -->
</div>

3. ngModel: The NgModel directive provides two-way data binding for form elements, syncing data between the model and the view.

Syntax:

<input [(ngModel)]="property">

Example:

HTML
<!-- app.component.html -->  <div class="container">     <h1 class="title">GeeksforGeeks</h1>      <div class="content">         <div [ngClass]="{'highlight': isHighlighted, 'italic': isItalic}">             This div's classes are dynamically applied based on conditions.         </div>          <div [ngStyle]="{'color': textColor, 'font-size': fontSize + 'px'}">             This div's styles are dynamically applied based on properties.         </div>          <input type="text" [(ngModel)]="username" class="input-field">         <p class="greeting">Hello, {{ username }}!</p>     </div> </div> 
CSS
/* app.component.css */  .container {     text-align: center; }  .title {     color: green; }  .content {     margin-top: 20px; }  .input-field {     margin-top: 20px;     padding: 10px;     border: 1px solid #ccc;     border-radius: 5px; }  .greeting {     margin-top: 20px; } 
JavaScript
// app.component.ts  import { Component } from '@angular/core';  @Component({     selector: 'app-root',     templateUrl: './app.component.html',     styleUrls: ['./app.component.css'] })  export class AppComponent {     isHighlighted: boolean = true;     isItalic: boolean = false;     textColor: string = 'blue';     fontSize: number = 18;     username: string = ''; } 
JavaScript
//app.module.ts  import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms';  import { AppComponent } from './app.component';  @NgModule({     declarations: [         AppComponent     ],     imports: [         BrowserModule,         FormsModule     ],     providers: [],     bootstrap: [AppComponent] }) export class AppModule { } 

Output:

builtin1

3. Structural Directives

Structural directives are responsible for manipulating the DOM layout by adding, removing, or manipulating elements based on conditions. They are denoted by an asterisk (*) preceding the directive name and are commonly used to alter the structure of the DOM based on conditions. Examples include , , and ngSwitch.

Built-in Attribute Directives:

1. ngIf: The ngIf directive conditionally includes or removes an element based on a provided expression.

Syntax:

<element *ngIf="condition">
<!-- Content to display when condition is true -->
</element>

2. ngFor: The ngFor directive iterates over a collection and instantiates a template once for each item in the collection.

Syntax:

<element *ngFor="let item of items">
<!-- Content to repeat for each item -->
</element>

3. ngSwitch: The ngSwitch directive is similar to a switch statement in programming languages. It displays one element from a set of elements based on a provided expression.

Syntax:

<element [ngSwitch]="expression">
<element *ngSwitchCase="value1"> <!-- Content for case 1 -->
</element>
<element *ngSwitchCase="value2"> <!-- Content for case 2 -->
</element>
<!-- More ngSwitchCase elements for other cases -->
<element *ngSwitchDefault> <!-- Default content -->
</element>
</element>

Example:

HTML
<!-- app.component.html -->  <div class="container">     <h1 class="title">GeeksforGeeks</h1>      <div class="content">         <div *ngIf="isLoggedIn" class="message">             Welcome to {{ username }}!         </div>          <ul *ngIf="items.length > 0" class="list">             <li *ngFor="let item of items" class="list-item">                 {{ item }}             </li>         </ul>          <div [ngSwitch]="color" class="color-switch">             <p *ngSwitchCase="'red'" class="color-message">Red color selected</p>             <p *ngSwitchCase="'blue'" class="color-message">Blue color selected</p>             <p *ngSwitchCase="'green'" class="color-message">Green color selected</p>             <p *ngSwitchDefault class="color-message">Please select a color</p>         </div>     </div> </div> 
CSS
/* app.component.css */  .container {     text-align: center; }  .title {     color: green; }  .content {     margin-top: 20px; }  .message {     font-size: 20px;     color: green;     margin-bottom: 20px; }  .list {     list-style-type: none;     padding: 0; }  .list-item {     font-size: 16px;     margin-bottom: 5px; }  .color-switch {     margin-top: 20px; }  .color-message {     font-size: 18px;     margin-top: 10px; } 
JavaScript
// app.component.ts  import { Component } from '@angular/core';  @Component({     selector: 'app-root',     templateUrl: './app.component.html',     styleUrls: ['./app.component.css'] }) export class AppComponent {     isLoggedIn: boolean = true;     username: string = 'GFG';     items: string[] = ['Item 1', 'Item 2', 'Item 3'];     color: string = 'red'; } 

Output:

Screenshot-2024-03-21-212306


Next Article
Built-in directives in Angular

B

bishalpaul34
Improve
Article Tags :
  • Web Technologies
  • AngularJS
  • AngularJS-Directives

Similar Reads

    Built-in Structural Directives in Angular
    Directives in Angular are nothing but the classes that allow us to add and modify the behavior of elements. Using directives in angular we can modify the DOM (Document Object Module) styles, handle user functionality, and much more. In this article, we will see more about Built-in structural directi
    3 min read
    Attribute Directives in Angular
    Attribute directives are a powerful tool that allows you to manipulate the behavior and appearance of HTML elements. In this article, you will see the fundamentals of attribute directives. Table of Content What are Attribute Directive?Benefits of Attribute DirectiveTypes of Attribute DirectivesSteps
    5 min read
    Recursion in Angular Directives
    Recursion in Angular directives refers to the ability of a directive to include instances of itself within its template. This allows for the creation of nested structures and dynamic rendering based on the data. Recursive directives are useful when dealing with hierarchical data or tree-like structu
    4 min read
    AngularJS ng-non-bindable Directive
    The ng-non-bindable Directive in AngularJS is used to specify that the specific content of HTML should not be compiled i.e the contents should be ignored by AngularJS. It can be used when we want to display code snippets instead of compiled output. Syntax: <element ng-non-bindable> Contents...
    1 min read
    AngularJS ng-init Directive
    The ng-init Directive is used to initialize AngularJS Application data. It defines the initial value for an AngularJS application and assigns values to the variables. The ng-init directive defines initial values and variables for an AngularJS application. Syntax: <element ng-init = "expression"
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences