2. Structural Directives - ngIf

 2.a Structural Directives - ngIf

Create a login form with username and password fields. If the user enters the correct credentials, it should render a "Welcome <<username>>" message otherwise it should render "Invalid Login!!! Please try again..." message


Step 1: Generate a new component

ng generate component login


step 2: Update the login component template Open the login.component.html file and replace its content with the following code:

<div *ngIf="isLoggedIn; else loginForm"> <h2>Welcome {{ username }}!</h2> </div> <ng-template #loginForm> <form (ngSubmit)="submitForm()"> <div> <label for="username">Username:</label> <input type="text" id="username" [(ngModel)]="username" required> </div> <div> <label for="password">Password:</label> <input type="password" id="password" [(ngModel)]="password" required> </div> <button type="submit">Login</button> </form> <div *ngIf="!isValidLogin" class="error-message"> Invalid Login!!! Please try again... </div> </ng-template>


Step 3: Update the login component class Open the login.component.ts file and update its content with the following code:


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


@Component({

  selector: 'app-login',

  templateUrl: './login.component.html',

  styleUrls: ['./login.component.css']

})

export class LoginComponent {

  username: string="";

  password: string="";

  isLoggedIn: boolean = false;

  isValidLogin: boolean = true;


  submitForm() {

    // Replace the following logic with your own authentication logic

    if (this.username === 'yourUsername' && this.password === 'yourPassword') {

      this.isLoggedIn = true;

      this.isValidLogin = true;

    } else {

      this.isLoggedIn = false;

      this.isValidLogin = false;

    }

  }

}

Step 4: Add the LoginComponent to a module Open the module file (e.g., app.module.ts) where you want to use the LoginComponent and import it:

import { LoginComponent } from './login/login.component';

then, add the LoginComponent to the declarations array in the @NgModule decorator:

@NgModule({ declarations: [ LoginComponent // other components ], // other module properties }) export class AppModule { }

Include forms module at the required places as below
in app.module.ts

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; // Import FormsModule import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule, FormsModule], // Add FormsModule to imports bootstrap: [AppComponent] }) export class AppModule {}

As alast step add <app-login></app-login> to app.component.html file

2.b. ngFor Create a courses array and rendering it in the template using ngFor directive in a list format

In your component file (e.g., app.component.ts), define an array of courses:

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { courses: string[] = ['Math', 'Science', 'History', 'English']; }


in your component's template file (e.g., app.component.html), use the ngFor directive to iterate over the courses array and render it in a list format:


<h2>Courses:</h2> <ul> <li *ngFor="let course of courses">{{ course }}</li> </ul>


2.c

ngSwitch Display the correct option based on the value passed to ngSwitch directive.

In your component file (e.g., app.component.ts), define a variable to hold the value that determines the option to display. Let's call it selectedOption:

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { selectedOption: string = 'option1'; }

In your component's template file (e.g., app.component.html), use the ngSwitch directive to determine which option to display based on the value of selectedOption:

<div [ngSwitch]="selectedOption"> <div *ngSwitchCase="'option1'"> Option 1 is selected. </div> <div *ngSwitchCase="'option2'"> Option 2 is selected. </div> <div *ngSwitchCase="'option3'"> Option 3 is selected. </div> <div *ngSwitchDefault> No option is selected. </div> </div>


In the above code, we use the [ngSwitch] attribute to bind the selectedOption value to the ngSwitch directive. The ngSwitchCase directive is used to define the different options based on their values. The ngSwitchDefault directive is used to handle the case when none of the specified options match the selectedOption value.

2.d. Custom Structural Directive

Create a custom structural directive called 'repeat' which should repeat the element
given a number of times.


To create a custom structural directive in Angular called 'repeat', we'll define a directive class and use the @Directive decorator. Structural directives in Angular manipulate the DOM by adding, removing, or updating elements based on the conditions they define.

  1. Create a new TypeScript file for the directive. For example, repeat.directive.ts.

  2. Import the necessary dependencies:


import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

Decorate the class with the @Directive decorator, specifying the selector and any inputs it might take:


@Directive({ selector: '[appRepeat]' })

Define the class for the directive:

export class RepeatDirective { constructor( private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef ) { } @Input('appRepeat') set repeat(times: number) { this.viewContainer.clear(); for (let i = 0; i < times; i++) { this.viewContainer.createEmbeddedView(this.templateRef); } } }


  1. Explanation of the code:
  • We inject TemplateRef and ViewContainerRef into the directive's constructor. TemplateRef represents the template associated with the directive, and ViewContainerRef allows us to manipulate the view where the directive is applied.
  • We define an input property named repeat using the @Input decorator. This input will take the number of times the element should be repeated.
  • When the repeat input changes, the set repeat method will be called. Inside this method, we clear the view container and then create the embedded view of the template times number of times. This will repeat the element accordingly.
  1. Finally, add the RepeatDirective to your Angular module's declarations array to make it available throughout the application.

For example, if you are using the directive in the AppModule, it will look like this


import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { RepeatDirective } from './repeat.directive'; @NgModule({ declarations: [ AppComponent, RepeatDirective ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

Now, you can use the 'appRepeat' directive in your HTML templates like this:



<ng-container *appRepeat="3">
  <p>This paragraph will be repeated 3 times.</p>
</ng-container>

Output:

This paragraph will be repeated 3 times.
This paragraph will be repeated 3 times.
This paragraph will be repeated 3 times.




Comments

Popular posts from this blog

9. Angular and MongoDBs

1. a. Angular Application Setup