0% found this document useful (0 votes)
17 views

MERN STACK LAB MODULE final cse

Lab module

Uploaded by

susmithalanka2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

MERN STACK LAB MODULE final cse

Lab module

Uploaded by

susmithalanka2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

MEAN STACK LAB MODULE -2

1A)Angular application setup.

To set up Angular on your system, follow these steps:

### 1. **Install Node.js**

Angular requires Node.js and npm (Node Package Manager), which are included with Node.js installation.

- Download and install Node.js from the official website: [Node.js](https://nodejs.org/)

- Verify installation by running the following commands in your terminal:

‘ ``command prompt code:

node -v

npm -v

```

### 2. **Install Angular CLI**

The Angular CLI (Command Line Interface) is used to create, build, and manage Angular projects.

- To install Angular CLI globally, run the following command:

``` command prompt code:

npm install -g @angular/cli

### 3. **Create a New Angular Project**

Now, create a new Angular project using the Angular CLI:

- Navigate to the directory where you want to create the project:

```command prompt code:

ng new project-name

```

You will be prompted to configure the project. Choose the appropriate options like adding Angular routing and
selecting the style format (CSS, SCSS, etc.).
### 4. **Navigate to the Project Folder**

Move into the newly created Angular project folder:

``` command prompt code:

cd project-name

```

### 5. **Run the Application**

Start the development server by running:

``` command prompt code:

ng serve

```

- Open a browser and navigate to `http://localhost:4200/` to see your Angular app running.

1B) Create a new component called hello and render hello on the page

After Angular app setup

Run a command to generate new component

“”ng generate component component_name””

Then change the script of app.component_name.html

1c)Add a event to hello component template and when it is clicked it should change the name

App.component.ts

Code:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
standalone: true, // Marking the component as standalone
template: `
<div class="hello-card" (click)="toggleUser()">
<h2>Hello, {{ currentUser }}!</h2>
</div>
`,
styles: [`
.hello-card {
background-color: #f9f9f9;
border: 1px solid #ddd;
border-radius: 8px;
padding: 20px;
text-align: center;
max-width: 300px;
margin: 50px auto;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
cursor: pointer;
}
`]
})
export class AppComponent {
currentUser: string = 'User 1';

toggleUser() {
this.currentUser = this.currentUser === 'User 1' ? 'User 2' : 'User 1';
}
}
2A)create a login form with user name and password fields if the user enter the correct
details it should render a welcome otherwise invalid login using “ngif” in angular
code:

App.component.ts

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

import { FormsModule } from '@angular/forms'; // Importing FormsModule for


ngModel binding
import { CommonModule } from '@angular/common'; // Importing CommonModule for
ngIf directive

@Component({
selector: 'app-root',
standalone: true, // Use standalone component
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
imports: [FormsModule, CommonModule], // Importing necessary modules
})
export class AppComponent {
username: string = '';
password: string = '';
isAuthenticated: boolean = false;
invalidCredentials: boolean = false;

correctUsername = 'user123';
correctPassword = 'pass123';

login() {
if (this.username === this.correctUsername && this.password ===
this.correctPassword) {
this.isAuthenticated = true;
this.invalidCredentials = false;
} else {
this.invalidCredentials = true;
this.isAuthenticated = false;
}
}
}
2B)use “ngfor” Create a courses array and rendering it in the template using ngFor directive in
a list format.

Code: (app.component.ts)

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

import { CommonModule } from '@angular/common';

@Component({

selector: 'app-root',

standalone: true,

template: `

<h1>Fruit List</h1>

<ul>

<li *ngFor="let fruit of fruits" (click)="selectFruit(fruit)">

{{ fruit }}

</li>

</ul>

`,

imports: [CommonModule]

})

export class AppComponent {

fruits: string[] = ['Apple', 'Banana', 'Orange', 'Mango', 'Grapes'];

selectFruit(fruit: string) {

console.log(fruit); // Logs selected fruit to the console

}}
2C)display the correct option based on value passed to the “ngswitch” directive

Code(app.component.ts):

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

import { CommonModule } from '@angular/common';

@Component({

selector: 'app-root',

standalone: true,

template: `

<div class="container">

<h1>Fruit List</h1>

<ul class="fruit-list">

<li *ngFor="let fruit of fruits" (click)="selectFruit(fruit)" class="fruit-item">

{{ fruit }}

</li>

</ul>

<h2>Selected Fruit Details:</h2>

<div class="fruit-details" [ngSwitch]="selectedFruit">

<p *ngSwitchCase="'Apple'">Apple is a sweet, edible fruit produced by an apple tree.</p>

<p *ngSwitchCase="'Banana'">Bananas are elongated, edible fruits produced by several kinds of large
herbaceous flowering plants.</p>

<p *ngSwitchCase="'Orange'">Oranges are juicy citrus fruits that are sweet and tangy.</p>

<p *ngSwitchCase="'Mango'">Mangoes are a stone fruit known for their sweetness and vibrant color.</p>

<p *ngSwitchCase="'Grapes'">Grapes are small, sweet fruits that grow in clusters on vines.</p>

<p *ngSwitchDefault>Select a fruit to see its details.</p>

</div>

</div>
`,

styles: [`

.container {

max-width: 600px;

margin: 0 auto;

padding: 20px;

font-family: Arial, sans-serif;

background-color: #f9f9f9;

border-radius: 8px;

box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

h1 {

text-align: center;

color: #333;

.fruit-list {

list-style-type: none;

padding: 0;

.fruit-item {

padding: 10px;

margin: 5px 0;

background-color: #e0f7fa;

border: 1px solid #b2ebf2;

border-radius: 4px;
cursor: pointer;

transition: background-color 0.3s;

.fruit-item:hover {

background-color: #b2ebf2;

.fruit-details {

margin-top: 20px;

padding: 10px;

background-color: #fff3e0;

border: 1px solid #ffccbc;

border-radius: 4px;

h2 {

color: #555;

`],

imports: [CommonModule]

})

export class AppComponent {

fruits: string[] = ['Apple', 'Banana', 'Orange', 'Mango', 'Grapes'];

selectedFruit: string = '';

selectFruit(fruit: string) {

this.selectedFruit = fruit;

}}
2D)create custom structural directive called repeat which should repeat the element given a
number of times.

import { Component, Directive, Input, TemplateRef, ViewContainerRef } from


'@angular/core';
import { FormsModule } from '@angular/forms';

@Directive({
selector: '[repeat]',
standalone: true // Mark the directive as standalone
})
export class RepeatDirective {
@Input() set repeat(times: number) {
this.viewContainer.clear(); // Clear any existing views
for (let i = 0; i < times; i++) {
this.viewContainer.createEmbeddedView(this.templateRef); // Create the
element specified times
}
}

constructor(private templateRef: TemplateRef<any>, private viewContainer:


ViewContainerRef) {}
}

@Component({
selector: 'app-root',
template: `
<div>
<label for="repeatTimes">Enter number of repetitions: </label>
<input id="repeatTimes" type="number" [(ngModel)]="repeatCount" />
</div>

<div *repeat="repeatCount">
<p>This element is repeated {{ repeatCount }} times!</p>
</div>
`,
standalone: true,
imports: [RepeatDirective, FormsModule],

})
export class AppComponent {
repeatCount = 1; // Default value for repetitions
}
1D)progressively building poolcarz applications

first create a new .ts file in app directory

car.service.ts

code:

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

export interface Car {

id: number;

model: string;

year: number;

@Injectable({

providedIn: 'root'

})

export class CarService {

private cars: Car[] = [

{ id: 1, model: 'Toyota Camry', year: 2020 },

{ id: 2, model: 'Honda Accord', year: 2021 }

];

getCars(): Car[] {

return this.cars;

addCar(car: Car): void {

this.cars.push(car);

then create a car component


Code:

Ng generate component car

And modify the car.component.ts


code:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';

import { CarService, Car } from '../car.service';

import { FormsModule } from '@angular/forms';

import { CommonModule } from '@angular/common';

@Component({

selector: 'app-car',

standalone: true,

template: `

<div class="container">

<h2>PoolCarz Management</h2>

<form (submit)="addCar(); $event.preventDefault()">

<div class="input-group">

<input

[(ngModel)]="newCar.model"

[ngModelOptions]="{standalone: true}"

placeholder="Car Model"

required

/>

<input

[(ngModel)]="newCar.year"

type="number"

[ngModelOptions]="{standalone: true}"
placeholder="Year"

required

/>

<button type="submit">Add Car</button>

</div>

</form>

<ul class="car-list">

<li *ngFor="let car of cars" class="car-item">{{ car.model }} ({{ car.year }})</li>

</ul>

</div>

`,

styles: [`

.container {

max-width: 600px;

margin: auto;

padding: 20px;

border: 1px solid #ddd;

border-radius: 8px;

box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

background-color: #f9f9f9;

font-family: Arial, sans-serif;

h2 {

text-align: center;

margin-bottom: 20px;

color: #333;
}

.input-group {

display: flex;

flex-wrap: wrap;

justify-content: space-between;

input {

flex: 1;

min-width: 200px; /* Minimum width for responsiveness */

padding: 10px;

margin-right: 10px;

border: 1px solid #ccc;

border-radius: 4px;

transition: border-color 0.3s;

input:focus {

border-color: #007bff; /* Bootstrap primary color */

outline: none;

box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);

button {

padding: 10px 15px;

background-color: #007bff; /* Bootstrap primary color */


color: white;

border: none;

border-radius: 4px;

cursor: pointer;

transition: background-color 0.3s;

button:hover {

background-color: #0056b3; /* Darker shade on hover */

.car-list {

list-style-type: none;

padding: 0;

margin-top: 20px;

.car-item {

padding: 10px;

border-bottom: 1px solid #eee;

transition: background-color 0.3s;

.car-item:hover {

background-color: #f1f1f1; /* Light gray background on hover */

}
@media (max-width: 600px) {

.input-group {

flex-direction: column;

input {

margin-right: 0;

margin-bottom: 10px;

`],

encapsulation: ViewEncapsulation.None,

imports: [FormsModule, CommonModule]

})

export class CarComponent implements OnInit {

cars: Car[] = [];

newCar: Car = { id: 0, model: '', year: new Date().getFullYear() };

constructor(private carService: CarService) {}

ngOnInit(): void {

this.cars = this.carService.getCars();

addCar(): void {

if (this.newCar.model && this.newCar.year) {

this.newCar.id = this.cars.length + 1; // Assign a simple ID


this.carService.addCar(this.newCar); // Add the new car to the service

this.cars = this.carService.getCars(); // Update the local cars array

this.newCar = { id: 0, model: '', year: new Date().getFullYear() }; // Reset the form

}}

Make sure the routing in

App.routing.ts

Code:

import { Routes } from '@angular/router';

import { CarComponent } from './car/car.component';

export const routes: Routes = [

{path: "", component: CarComponent}

];
3B)apply multiple css classes to the text using ng class directive

Code:

create a new component

ng generate component responsivetext

modify responsivetext.component.ts

code:

import { CommonModule } from '@angular/common';

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

@Component({

selector: 'app-responsive-text',

standalone: true,

template: `

<div class="text-container" [ngClass]="textClasses">

This is responsive text with multiple classes.

</div>

<div class="button-container">

<button (click)="toggle('isLarge')">Toggle Large</button>

<button (click)="toggle('isHighlighted')">Toggle Highlight</button>

<button (click)="toggle('isBold')">Toggle Bold</button>

<button (click)="toggle('isItalic')">Toggle Italic</button>

<button (click)="toggle('isUnderlined')">Toggle Underline</button>

<button (click)="toggle('isRed')">Toggle Red</button>

<button (click)="toggle('isGreen')">Toggle Green</button>

<button (click)="toggle('isBlue')">Toggle Blue</button>

</div>

`,
styles: [`

.text-container {

font-size: 16px;

padding: 10px;

margin: 20px;

transition: all 0.3s ease;

.large {

font-size: 24px;

color: blue;

.highlight {

background-color: yellow;

.bold {

font-weight: bold;

.italic {

font-style: italic;

.underline {

text-decoration: underline;

.red {

color: red;

.green {
color: green;

.blue {

color: blue;

.button-container {

margin: 20px;

align-items: center;

display:flex;

button {

margin-right: 5px;

padding: 10px;

cursor: pointer;

background-color: #007bff;

color: white;

border: none;

border-radius: 5px;

transition: background-color 0.3s ease;

button:hover {

background-color: #0056b3;

`],

imports: [CommonModule]

})
export class ResponsiveTextComponent {

// Initialize style toggles

isLarge = false;

isHighlighted = false;

isBold = false;

isItalic = false;

isUnderlined = false;

isRed = false;

isGreen = false;

isBlue = false;

// Mapping class names to toggle variables

get textClasses() {

return {

large: this.isLarge,

highlight: this.isHighlighted,

bold: this.isBold,

italic: this.isItalic,

underline: this.isUnderlined,

red: this.isRed,

green: this.isGreen,

blue: this.isBlue

};

// Create a union type for the toggleable properties

private toggleableStyles = [
'isLarge',

'isHighlighted',

'isBold',

'isItalic',

'isUnderlined',

'isRed',

'isGreen',

'isBlue'

] as const;

// Toggle the state of a given style

toggle(style: typeof this.toggleableStyles[number]) {

this[style] = !this[style];

app.routing.ts

code:

import { Routes } from '@angular/router';

import { ResponsiveTextComponent } from './responsivetext/responsivetext.component';

export const routes: Routes = [

{path: "", component: ResponsiveTextComponent}

];
3a)apply multiple css properties to a paragraph in a component using “ngstyle”

create a new component

ng generate component para

modify para.component.ts

code:

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

import { CommonModule } from '@angular/common';

@Component({

selector: 'app-para',

standalone: true,

imports: [CommonModule],

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

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

})

export class ParagraphStylerComponent {

// Updated CSS styles defined as an object

paragraphStyles = {

color: '#555', // Dark text color for contrast

fontSize: '18px',

lineHeight: '1.6', // Improved line height for readability

textAlign: 'justify',

padding: '20px', // Increased padding

border: '1px solid #ddd', // Light border color

borderRadius: '20px', // More rounded corners

backgroundColor: '#f9f9f9',

margin: '10px',

boxShadow: '0 4px 10px rgba(0,0,0,0.1)', // Deeper shadow for depth


transition: 'all 0.3s ease' // Smooth transitions for hover effects

};

paragraphContent = "This is a responsive paragraph styled using Angular's ngStyle. You can easily change the
styles to fit your design.";

App.routing.ts

import { Routes } from '@angular/router';

import { ParagraphStylerComponent } from './para/para.component';

export const routes: Routes = [

{path: "", component: ParagraphStylerComponent}

];
3c)Custom attribute directive
Create a .ts file in app directory

Show-message.directive.ts

Code:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({

selector: '[appShowMessage]',

standalone: true

})

export class ShowMessageDirective {

@Input('appShowMessage') message!: string;

private messageElement?: HTMLElement;

private buttonElement?: HTMLButtonElement;

private isRed: boolean = false; // Track color state

constructor(private el: ElementRef) {}

@HostListener('click') onClick() {

// Clear any previous content

if (!this.messageElement) {

this.el.nativeElement.innerHTML = '';

// Create and append the message element

this.messageElement = document.createElement('p');

this.messageElement.textContent = this.message;
this.messageElement.style.margin = '10px 0';

this.el.nativeElement.appendChild(this.messageElement);

// Create and append the button element

this.buttonElement = document.createElement('button');

this.buttonElement.textContent = 'Toggle Text Color';

this.buttonElement.style.marginTop = '10px';

this.buttonElement.style.cursor = 'pointer';

this.el.nativeElement.appendChild(this.buttonElement);

// Add click event to the button

this.buttonElement.addEventListener('click', (event) => {

event.stopPropagation(); // Prevent triggering the directive's click

this.toggleColor(); // Call toggle function

});

private toggleColor() {

// Toggle the color of the message

this.isRed = !this.isRed;

this.messageElement!.style.color = this.isRed ? '#ff0000' : ''; // Change to red or default

Then generate a new component

Ng generate component message


Then modify message.component.ts

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

import { ShowMessageDirective } from '../show-message.directive'; // Adjust the path as necessary

@Component({

selector: 'app-message-display',

standalone: true,

template: `

<div style="padding: 20px; text-align: center;" appShowMessage="Hello, World!">

<button style="padding: 10px; cursor: pointer;">

Click me to show message

</button>

</div>

`,

styles: [],

imports: [ShowMessageDirective] // Include the directive here

})

export class MessageDisplayComponent {}

must set a routing

import { Routes } from '@angular/router';

import { MessageDisplayComponent } from './message/message.component';

export const routes: Routes = [

{path: "", component: MessageDisplayComponent}

];

You might also like