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

FST_React_Angular

The document outlines various React concepts including the use of Class and Function components, the MERN stack's role in a library management system, and methods for rendering components from arrays. It also explains how to read props in child components, manage state and interactivity in lists, and implement conditional rendering. Each section includes code examples and explanations to illustrate the concepts effectively.

Uploaded by

Shriya Sridhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

FST_React_Angular

The document outlines various React concepts including the use of Class and Function components, the MERN stack's role in a library management system, and methods for rendering components from arrays. It also explains how to read props in child components, manage state and interactivity in lists, and implement conditional rendering. Each section includes code examples and explanations to illustrate the concepts effectively.

Uploaded by

Shriya Sridhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

REACT :

1. Create a webpage to demonstrate the use of Class and


function components.
Ans: 🔹 Function Components
 The simpler and modern way.
 They are just JavaScript functions that return JSX.
 Can use React Hooks (like useState, useEffect, etc.).
🔹 Class Components
 An older style, still used in some codebases.
 Defined using ES6 class syntax.
 Must have a render() method that returns JSX.
 Can use state and lifecycle methods directly.

✅ Simple Example: Class vs Function Components


👨‍🏫 Code:
jsx
CopyEdit
// FunctionComponent.js
function FunctionComponent() {
return <h2>This is a Function Component</h2>;
}

// ClassComponent.js
import React from 'react';

class ClassComponent extends React.Component {


render() {
return <h2>This is a Class Component</h2>;
}
}

// App.js
import React from 'react';
import FunctionComponent from './FunctionComponent';
import ClassComponent from './ClassComponent';

export default function App() {


return (
<div>
<h1>Class and Function Components Demo</h1>
<FunctionComponent />
<ClassComponent />
</div>
);
}

2. Suppose you are developing a web application for an online


library management system. Describe the role of each component
(MongoDB, Express, React and Nodejs) in implementing a feature
where users can search for books, view book details, and place
requests to borrow books. (10 marks)
Ans: Here’s a simple and clear breakdown of how each part of the
MERN stack (MongoDB, Express, React, Node.js) plays a role in
building a book search and borrow request feature for an
Online Library Management System:

🔷 1. MongoDB (Database Layer)


 Role: Stores all the data related to books, users, and borrow
requests.
 Example data:
json
CopyEdit
{
"_id": "1",
"title": "The Alchemist",
"author": "Paulo Coelho",
"available": true,
"description": "A journey of self-discovery."
}
 When a user searches for a book or places a borrow request,
MongoDB is queried or updated accordingly.

🔷 2. Express (Backend/Server Layer)


 Role: Acts as the server and handles the API routes.
 Example routes:
o GET /api/books?title=alchemist → Search for books.
o GET /api/books/:id → View details of a specific book.
o POST /api/requests → Place a borrow request.
 It receives requests from the React frontend, communicates
with MongoDB, and sends back JSON responses.

🔷 3. React (Frontend/User Interface Layer)


 Role: Provides the interactive UI that users interact with.
 Users can:
o Type in the search bar to find books.
o Click on a book to view details.
o Click a “Request to Borrow” button.
 React sends HTTP requests to Express using fetch() or axios,
and dynamically updates the UI based on the data received.

🔷 4. Node.js (Runtime Environment)


 Role: Runs the Express backend server.
 It uses JavaScript to handle server-side logic like:
o Connecting to MongoDB.
o Handling incoming requests and responses.
o Validating borrow requests.
 Without Node.js, Express cannot run.

✅ Example Flow:
1. User types “Alchemist” in the React search bar.
2. React calls GET /api/books?title=alchemist.
3. Express (Node.js) receives the request, queries MongoDB.
4. MongoDB returns matching books to Express, which sends
them back to React.
5. React displays the results.
6. User clicks “Request to Borrow” → React sends POST
/api/requests.
7. Express saves the request in MongoDB and confirms to the
user.

3. How to render components from an array using JavaScript’s


map()
Ans: You will rely on JavaScript features like for loop and the array
map() function to render lists of
components.
For example, let’s say you have an array of products:

const products = [
{ title: 'Cabbage', id: 1 },
{ title: 'Garlic', id: 2 },
{ title: 'Apple', id: 3 },
];
Inside your component, use the map() function to transform an
array of products into an array of
<li> items:
const listItems = products.map(product =>
<li key={product.id}>
{product.title}
</li>
);
return (
<ul>{listItems}</ul>
);
Notice how <li> has a key attribute. For each item in a list, you
should pass a string or a number
that uniquely identifies that item among its siblings. Usually, a key
should be coming from your
data, such as a database ID. React uses your keys to know what
happened if you later insert, delete,
or reorder the items.

4. Explain with an example how to read props inside the child


component and how props change over time.
Ans: Then, pass the state down from MyApp to each MyButton,
together with the shared click handler.
You can pass information to MyButton using the JSX curly braces,
just like you previously did with
built-in tags like <img>:
export default function MyApp() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>Counters that update together</h1>
<MyButton count={count} onClick={handleClick} />
<MyButton count={count} onClick={handleClick} />
</div>
);
}
The information you pass down like this is called props. Now the
MyApp component contains the
count state and the handleClick event handler, and passes both of
them down as props to each of the
buttons.
Finally, change MyButton to read the props you have passed from
its parent component:
function MyButton({ count, onClick }) {
return (
<button onClick={onClick}>
Clicked {count} times
</button>
);
}
When you click the button, the onClick handler fires. Each button’s
onClick prop was set to the
handleClick function inside MyApp, so the code inside of it runs.
That code calls setCount(count +1), incrementing the count state
variable. The new count value is passed as a prop to each button,
so
they all show the new value. This is called “lifting state up”. By
moving state up, you’ve shared it
between components.
In React, props are used to pass data from a parent component
to a child component. You can read props in the child component
using destructuring or by accessing props.propertyName.
When the parent's state changes, and that state is passed as a
prop, the child component automatically gets the updated
value on re-render.
At first, count = 0 → Both buttons show "Clicked 0 times".You click a
button → count becomes 1 → Both buttons now show "Clicked 1
times". This shows that props change over time when the parent
component's state changes.

5. Interactivity in Webpages using React -update objects in an


array.
Ans: In React, when you have an array of objects (e.g. list of books,
tasks, etc.), and you want to update a specific object (like
marking a task complete), you use state and map() to create a new
updated array.
🔹 Complete Code Recap
jsx
CopyEdit
import { useState } from 'react';

export default function TaskList() {


const [tasks, setTasks] = useState([
{ id: 1, title: 'Buy groceries', completed: false },
{ id: 2, title: 'Do homework', completed: false },
{ id: 3, title: 'Read a book', completed: false },
]);

function markComplete(id) {
const updatedTasks = tasks.map(task =>
task.id === id ? { ...task, completed: true } : task
);
setTasks(updatedTasks);
}

return (
<div>
<h2>Task List</h2>
<ul>
{tasks.map(task => (
<li key={task.id}>
{task.title} - {task.completed ? '✅ Done' : '❌ Not Done'}
<button onClick={() => markComplete(task.id)}>Mark
Done</button>
</li>
))}
</ul>
</div>
);
}

🔍 Line-by-line Explanation

Line 1
js
CopyEdit
import { useState } from 'react';
 This imports the useState hook from React so we can use
state to store and update the task list.

Line 3
js
CopyEdit
export default function TaskList() {
 Defines a functional React component named TaskList.

Lines 4–8
js
CopyEdit
const [tasks, setTasks] = useState([
{ id: 1, title: 'Buy groceries', completed: false },
{ id: 2, title: 'Do homework', completed: false },
{ id: 3, title: 'Read a book', completed: false },
]);
 tasks is the state variable holding the array of tasks.
 setTasks is the function to update that state.
 useState(...) sets the initial value of tasks as an array of three
task objects.
Lines 10–14
js
CopyEdit
function markComplete(id) {
const updatedTasks = tasks.map(task =>
task.id === id ? { ...task, completed: true } : task
);
setTasks(updatedTasks);
}
 Defines a function called markComplete, which takes the id of
a task.
 .map() goes through each task in the array:
o If the task.id matches the id we passed, it returns a new
object with completed: true.
o If it doesn't match, it returns the task as-is.
 setTasks(updatedTasks) updates the state with the new task
list.

Lines 16–27
js
CopyEdit
return (
<div>
<h2>Task List</h2>
<ul>
{tasks.map(task => (
<li key={task.id}>
{task.title} - {task.completed ? '✅ Done' : '❌ Not Done'}
<button onClick={() => markComplete(task.id)}>Mark
Done</button>
</li>
))}
</ul>
</div>
);
 This is the UI (JSX) returned by the component.
 <ul> displays the list of tasks.
 {tasks.map(...)} loops over each task and returns a <li>
element for each.
o key={task.id} helps React track items.
o {task.title} shows the task name.
o {task.completed ? '✅ Done' : '❌ Not Done'} shows whether
it's done.
o <button onClick={...}> calls markComplete(task.id)
when clicked.

✅ Summary:
 This component maintains a list of tasks in state.
 It displays each task with a status and a button.
 Clicking the button updates that task’s completed field.
 React automatically re-renders the UI when the state
updates.

6. Create a webpage to implement Create and read Operations in


a list of items in an array using eventhandling.
Ans: import React, { useState } from 'react';

export default function ItemList() {


const [items, setItems] = useState([]); // Array to store items
const [itemInput, setItemInput] = useState(''); // Input state to
hold current input

// Handle creating a new item


function handleAddItem() {
if (itemInput.trim()) {
setItems([...items, itemInput]); // Add the new item to the list
setItemInput(''); // Clear the input field after adding item
}
}

// Handle updating the input field


function handleInputChange(event) {
setItemInput(event.target.value); // Update the input field with
user input
}

return (
<div>
<h2>Item List</h2>
<input
type="text"
value={itemInput}
onChange={handleInputChange} // Update input field
placeholder="Enter an item"
/>
<button onClick={handleAddItem}>Add Item</button> {/*
Trigger handleAddItem on click */}
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li> // Display each item in the list
))}
</ul>
</div>
);
}
Explanation Line by Line:
import React, { useState } from 'react';

Import React and the useState hook to manage the state in the
functional component.

export default function ItemList() {

Define the ItemList component, which will handle the list of items.

const [items, setItems] = useState([]);

Define the items state, which will store the array of items that the
user adds. Initially, it's an empty array.

const [itemInput, setItemInput] = useState('');

Define the itemInput state to store the current value in the input
field where the user types a new item.

function handleAddItem() {...}

Define the handleAddItem function that will be called when the user
clicks the "Add Item" button. This function will add the item in the
input field to the items list.

if (itemInput.trim()) {

Check if the input field is not empty (ignoring any spaces). This
prevents adding empty or whitespace-only items to the list.

setItems([...items, itemInput]);
Update the items array by adding the new item (itemInput) to the
list using the spread operator (...items) to retain the existing items
in the array.

setItemInput('');

Clear the input field by resetting the itemInput state to an empty


string after the item has been added to the list.

function handleInputChange(event) {...}

Define the handleInputChange function, which will update the


itemInput state whenever the user types something in the input
field.

setItemInput(event.target.value);

Set the itemInput state to the current value of the input field
(event.target.value).

return (...)

Return the JSX structure of the component that renders the UI for
this component.

<input type="text" value={itemInput}


onChange={handleInputChange} placeholder="Enter an item" />

Render an input field where the user can type the new item. The
value of this input is controlled by the itemInput state, and any
change in the input field triggers the handleInputChange function.

<button onClick={handleAddItem}>Add Item</button>

Render a button that calls the handleAddItem function when clicked.


This will add the item typed in the input field to the list.

<ul>{items.map((item, index) => (<li


key={index}>{item}</li>))}</ul>

Render a list (<ul>) of items. Each item in the items array is


mapped to an <li> element, and each item is displayed inside it.
The key={index} helps React efficiently re-render the list.
Webpage Output:
Initial State (Empty List)
Input field: [ ] (blank)

Add Item button: [Add Item]

After Adding Items:


Type "Buy groceries" in the input field, and click "Add Item":

List will show:

diff
Copy
Edit
- Buy groceries
Type "Do homework" in the input field, and click "Add Item":

List will show:

diff
Copy
Edit
- Buy groceries
- Do homework

7. Create a webpage to demonstrate conditional rendering


Ans: ✅ React Code (Simple version, for exam)
jsx
CopyEdit
import React, { useState } from 'react';

function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);

return (
<div>
<h1>Conditional Rendering Example</h1>

{isLoggedIn ? (
<p>Welcome back, User!</p>
):(
<p>Please log in to continue.</p>
)}
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? 'Log Out' : 'Log In'}
</button>
</div>
);
}

export default App;

🧠 Line-by-Line Explanation
Line 1:
js
CopyEdit
import React, { useState } from 'react';
 Imports React and the useState hook, which is used to manage
state in functional components.
Line 3:
js
CopyEdit
function App() {
 Declares a React functional component named App.
Line 4:
js
CopyEdit
const [isLoggedIn, setIsLoggedIn] = useState(false);
 Creates a state variable isLoggedIn with the default value
false.
 setIsLoggedIn is a function used to change the value of
isLoggedIn.
Line 6–16:
js
CopyEdit
return (
<div>
...
</div>
);
 Returns JSX (HTML-like syntax in React) that defines the
structure of what will be shown in the browser.
Line 7:
js
CopyEdit
<h1>Conditional Rendering Example</h1>
 Displays a title for the page.
Lines 9–13:
js
CopyEdit
{isLoggedIn ? (
<p>Welcome back, User!</p>
):(
<p>Please log in to continue.</p>
)}
 This is the conditional rendering part.
 If isLoggedIn is true, it shows the message "Welcome back,
User!"
 If isLoggedIn is false, it shows "Please log in to continue."
Line 15:
js
CopyEdit
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
 A button that toggles the login state when clicked.
 !isLoggedIn flips the current value (true becomes false, and
vice versa).
Line 16:
js
CopyEdit
{isLoggedIn ? 'Log Out' : 'Log In'}
 Button text changes based on the login status.
 Shows "Log Out" if user is logged in, otherwise shows "Log In".
Line 20:
js
CopyEdit
export default App;
 Exports the App component so it can be used in other parts of
the application.

8. Create a project using React Router with two pages, Home and
Films containing list of directors and the films.
Ans: App.js
jsx
CopyEdit
import { BrowserRouter, Routes, Route, Link } from 'react-router-
dom';
import Home from './Home';
import Films from './Films';
export default function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link> | <Link to="/films">Films</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/films" element={<Films />} />
</Routes>
</BrowserRouter>
);
}

Home.js
jsx
CopyEdit
export default function Home() {
return (
<div>
<h1>Welcome to Movie World</h1>
<p>Click on Films to explore directors and their works.</p>
</div>
);
}

Films.js
jsx
CopyEdit
export default function Films() {
const data = [
{ director: 'Christopher Nolan', films: ['Inception', 'Interstellar'] },
{ director: 'Steven Spielberg', films: ['E.T.', 'Jaws'] },
];

return (
<div>
<h1>Directors and Their Films</h1>
<ul>
{data.map((item, index) => (
<li key={index}>
<strong>{item.director}</strong>
<ul>
{item.films.map((film, i) => (
<li key={i}>{film}</li>
))}
</ul>
</li>
))}
</ul>
</div>
);
}

🧪 index.js (just renders the app)


jsx
CopyEdit
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

9. Explain React lifecycle with an example.

10. Create a webage to demonstrate the use of react hooks


11. Explain VIRTUAL DOM
Ans: React uses Virtual DOM, which can be thought of as a blueprint
of the DOM.
When any changes are made to React elements, the Virtual DOM is
updated.
The Virtual DOM finds the differences between it and the DOM and
re-renders
only the elements in the DOM that changed. This makes the Virtual
DOM faster
and more efficient than updating the entire DOM.

1.Component-Based Item Display and Filtering:

Task: Create a React component called GroceryItem that displays


the name, price, and quantity of a grocery item. Create another
component called GroceryList that renders a list of GroceryItem
components. Implement a filtering mechanism using a search input
field. When the user types in the search input, the GroceryList
should only display items whose names contain the search term.
Concepts: Component creation, props, state management (using
useState), list rendering (.map()), filtering arrays (.filter()).
import React, { useState } from 'react';

function GroceryItem({ name, price, quantity }) {


return (
<li>
{name} - ${price} (Qty: {quantity})
</li>
);
}

function GroceryList() {
const [searchTerm, setSearchTerm] = useState('');
const groceries = [
{ name: 'Apples', price: 1.5, quantity: 5 },
{ name: 'Bananas', price: 0.5, quantity: 10 },
{ name: 'Carrots', price: 0.8, quantity: 8 },
{ name: 'Milk', price: 2.0, quantity: 2 },
];

const filteredItems = groceries.filter(item =>


item.name.toLowerCase().includes(searchTerm.toLowerCase())
);

return (
<div>
<h2>Grocery List</h2>
<input
type="text"
placeholder="Search item"
value={searchTerm}
onChange={e => setSearchTerm(e.target.value)}
/>
<ul>
{filteredItems.map((item, index) => (
<GroceryItem
key={index}
name={item.name}
price={item.price}
quantity={item.quantity}
/>
))}
</ul>
</div>
);
}

export default GroceryList;

2.Cart Management with State and Event Handling:

Task: Extend the GroceryItem component to include an "Add to


Cart" button. Create a Cart component that displays the items
added to the cart and their total price. Implement functionality to
add items to the cart when the button is clicked and update the cart
display. Allow users to increase or decrease the quantity of items in
the cart.
Concepts: State management (using useState and potentially
useReducer for more complex state), event handling (onClick,
onChange), managing arrays of objects in state, calculating totals.
Ans: import React, { useState } from 'react';

function GroceryItem({ item, onAddToCart }) {


return (
<li>
{item.name} - ${item.price}
<button onClick={() => onAddToCart(item)}>Add to
Cart</button>
</li>
);
}

function Cart({ cartItems, onIncrease, onDecrease }) {


const total = cartItems.reduce(
(sum, item) => sum + item.price * item.quantity,
0
);

return (
<div>
<h2>Cart</h2>
<ul>
{cartItems.map((item, index) => (
<li key={index}>
{item.name} - ${item.price} × {item.quantity}
<button onClick={() =>
onIncrease(item.name)}>+</button>
<button onClick={() =>
onDecrease(item.name)}>-</button>
</li>
))}
</ul>
<h3>Total: ${total.toFixed(2)}</h3>
</div>
);
}

function GroceryApp() {
const items = [
{ name: 'Apples', price: 1.5 },
{ name: 'Bananas', price: 0.5 },
{ name: 'Carrots', price: 0.8 },
];

const [cart, setCart] = useState([]);

function addToCart(item) {
const found = cart.find(i => i.name === item.name);
if (found) {
const updated = cart.map(i =>
i.name === item.name ? { ...i, quantity: i.quantity + 1 } : i
);
setCart(updated);
} else {
setCart([...cart, { ...item, quantity: 1 }]);
}
}

function increaseQty(name) {
setCart(
cart.map(item =>
item.name === name ? { ...item, quantity: item.quantity +
1 } : item
)
);
}

function decreaseQty(name) {
setCart(
cart
.map(item =>
item.name === name
? { ...item, quantity: item.quantity - 1 }
: item
)
.filter(item => item.quantity > 0)
);
}

return (
<div>
<h1>Grocery Store</h1>
<ul>
{items.map((item, index) => (
<GroceryItem key={index} item={item}
onAddToCart={addToCart} />
))}
</ul>
<Cart
cartItems={cart}
onIncrease={increaseQty}
onDecrease={decreaseQty}
/>
</div>
);
}

export default GroceryApp;

3.Data Fetching and Asynchronous Operations:

Task: Simulate fetching grocery item data from an API (you can use
a local JSON file or a mock API). Display the fetched data in the
GroceryList component. Implement a loading state while the data is
being fetched and handle potential errors.
Concepts: Asynchronous operations (fetch or axios), useEffect hook
for side effects, handling loading states, error handling.
import React, { useState, useEffect } from 'react';

function GroceryList() {
const [items, setItems] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
// Simulating fetch from an API or local JSON file
fetch('https://mocki.io/v1/49aeb7f6-2ae4-4c68-bc7a-
7e23b9778124') // <-- Example mock API
.then(response => {
if (!response.ok) throw new Error('Network response was not
ok');
return response.json();
})
.then(data => {
setItems(data);
setLoading(false);
})
.catch(err => {
setError('Failed to fetch items');
setLoading(false);
});
}, []); // Runs once on component mount

if (loading) return <p>Loading items...</p>;


if (error) return <p>{error}</p>;

return (
<div>
<h2>Available Grocery Items</h2>
<ul>
{items.map((item, index) => (
<li key={index}>
{item.name} - ${item.price}
</li>
))}
</ul>
</div>
);
}

export default GroceryList;

4.Form Input and Validation for Adding New Items:

Task: Create a form component that allows users to add new


grocery items. The form should include input fields for the item
name, price, and quantity. Implement input validation to ensure that
all fields are filled and that the price and quantity are valid
numbers. Upon form submission, add the new item to the
GroceryList.
Concepts: Form handling, input validation, state management for
form inputs, event handling (onSubmit), adding items to an array in
state.

import React, { useState } from 'react';

function GroceryForm() {
const [items, setItems] = useState([]);
const [name, setName] = useState('');
const [price, setPrice] = useState('');
const [quantity, setQuantity] = useState('');
const [error, setError] = useState('');

function handleSubmit(e) {
e.preventDefault();

if (!name || !price || !quantity) {


setError('All fields are required');
return;
}

if (isNaN(price) || isNaN(quantity)) {
setError('Price and Quantity must be numbers');
return;
}

const newItem = {
name,
price: parseFloat(price),
quantity: parseInt(quantity),
};

setItems([...items, newItem]);

// Clear form
setName('');
setPrice('');
setQuantity('');
setError('');
}

return (
<div>
<h2>Add Grocery Item</h2>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Item Name"
value={name}
onChange={e => setName(e.target.value)}
/>
<input
type="text"
placeholder="Price"
value={price}
onChange={e => setPrice(e.target.value)}
/>
<input
type="text"
placeholder="Quantity"
value={quantity}
onChange={e => setQuantity(e.target.value)}
/>
<button type="submit">Add Item</button>
</form>
{error && <p style={{ color: 'red' }}>{error}</p>}
<ul>
{items.map((item, index) => (
<li key={index}>
{item.name} - ${item.price} x {item.quantity}
</li>
))}
</ul>
</div>
);
}

export default GroceryForm;

5.Routing and Navigation for Different Views:

Task: Use React Router to create different views for the application.
Implement routes for the grocery list, the cart, and a "New Item"
form. Create navigation links to switch between these views.
Concepts: React Router (installation and usage), route definition,
navigation using Link components, organizing application views.
📁 App.js
jsx
CopyEdit
import React from 'react';
import { BrowserRouter, Routes, Route, Link } from 'react-
router-dom';
import GroceryList from './GroceryList';
import Cart from './Cart';
import GroceryForm from './GroceryForm';

export default function App() {


return (
<BrowserRouter>
<div>
<nav>
<Link to="/">Grocery List</Link> |
<Link to="/cart">Cart</Link> |
<Link to="/add">Add Item</Link>
</nav>
<Routes>
<Route path="/" element={<GroceryList />} />
<Route path="/cart" element={<Cart />} />
<Route path="/add" element={<GroceryForm />} />
</Routes>
</div>
</BrowserRouter>
);
}

🧾 GroceryList.js (sample)
jsx
CopyEdit
import React from 'react';

export default function GroceryList() {


return (
<div>
<h2>Grocery List</h2>
<ul>
<li>Apples - $2</li>
<li>Bread - $1</li>
<li>Milk - $3</li>
</ul>
</div>
);
}

🧾 Cart.js (sample)
jsx
CopyEdit
import React from 'react';

export default function Cart() {


return (
<div>
<h2>Cart</h2>
<p>No items yet.</p>
</div>
);
}

Angular

1. Create an angular webpage using builtin and custom Pipes


Ans: 2. Create a Custom Pipe
Now, we will create a custom pipe and use some built-in pipes.
Run the following command to generate the custom pipe:
bash
CopyEdit
ng generate pipe capitalize
This will generate a file called capitalize.pipe.ts.
Edit this file as follows:
typescript
CopyEdit
// src/app/capitalize.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'capitalize'
})
export class CapitalizePipe implements PipeTransform {
transform(value: string): string {
if (!value) return value;
return value.charAt(0).toUpperCase() +
value.slice(1).toLowerCase();
}
}
Explanation:
1. Pipe Decorator: @Pipe({ name: 'capitalize' }) – This marks
the class as a pipe. The name defines how we will use the pipe
in the HTML template.
2. transform Method: This method is required in a custom pipe.
It receives a value (the string to be transformed) and returns
the transformed value. In this case, it capitalizes the first letter
of the string and converts the rest to lowercase.
3. Modify the App Component
Now, let’s use both built-in and custom pipes in the
app.component.html and app.component.ts.
app.component.ts
typescript
CopyEdit
// src/app/app.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'pipe-demo';
message = 'hello, angular pipes';
date = new Date();
}
Explanation:
1. Component Decorator: @Component defines the
component's selector (app-root), template URL
(app.component.html), and CSS styles.
2. Properties: The title, message, and date properties will be
used in the HTML template. date is an instance of Date, which
will demonstrate the use of built-in pipes.
app.component.html
html
CopyEdit
<!-- src/app/app.component.html -->
<div style="text-align:center">
<h1>{{ title }}</h1>
<p>{{ message | uppercase }}</p> <!-- Built-in uppercase pipe
-->

<p>{{ message | lowercase }}</p> <!-- Built-in lowercase pipe --


>

<p>{{ message | capitalize }}</p> <!-- Custom capitalize pipe --


>

<p>{{ date | date: 'fullDate' }}</p> <!-- Built-in date pipe -->
</div>

2. Createa page to illustrate


3. Event Binding
4. Data Binding
5. Style binding ‘
6. Property Binding
7. Two -way binding
1. Event Binding
What it is:
Event binding lets your app respond to user actions like button
clicks.
📄 Example: Show alert on button click
html
CopyEdit
<!-- app.component.html -->
<button (click)="showAlert()">Click Me</button>
ts
CopyEdit
// app.component.ts
export class AppComponent {
showAlert() {
alert('Button was clicked!');
}
}
✅ Explanation:
 (click)="showAlert()": This binds the button’s click event to the
showAlert method.

2. Property Binding
What it is:
It sets a DOM property of an element to a component’s property.
📄 Example: Disable a button using property
html
CopyEdit
<!-- app.component.html -->
<button [disabled]="isDisabled">Can't Click Me</button>
ts
CopyEdit
// app.component.ts
export class AppComponent {
isDisabled = true;
}
✅ Explanation:
 [disabled]="isDisabled": Binds the button's disabled property
to the component variable.

3. Data Binding (Interpolation)


What it is:
Interpolation lets you show dynamic data from the component in
the template.
📄 Example: Show a welcome message
html
CopyEdit
<!-- app.component.html -->
<h1>Welcome, {{ username }}!</h1>
ts
CopyEdit
// app.component.ts
export class AppComponent {
username = 'John';
}
✅ Explanation:
 {{ username }}: Displays the value of the username property.

4. Style Binding
What it is:
You can change the CSS styles of an element dynamically.
📄 Example: Change text color
html
CopyEdit
<!-- app.component.html -->
<p [style.color]="textColor">This is styled text.</p>
ts
CopyEdit
// app.component.ts
export class AppComponent {
textColor = 'blue';
}
✅ Explanation:
 [style.color]="textColor": Binds the color style to the variable
textColor.

5. Two-Way Binding
What it is:
It allows data to flow both ways: from the component to the input
and from the input back to the component.
📄 Example: Update name live
html
CopyEdit
<!-- app.component.html -->
<input [(ngModel)]="name">
<p>Your name is: {{ name }}</p>
ts
CopyEdit
// app.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
name = '';
}
✅ Note: You must import FormsModule in your app.module.ts for
[(ngModel)] to work:
ts
CopyEdit
import { FormsModule } from '@angular/forms';

@NgModule({
imports: [BrowserModule, FormsModule],
})
export class AppModule {}
✅ Explanation:
 [(ngModel)]="name": Syncs the input field and the name
variable both ways.

8. Explain three types of directives with examples


9. Programs related to structural directives,attribute directives
10. Programs related to component and custom directive.
✅ 1. Component Directives

These are custom components you create. Every Angular component is a directive with a template.

🔹 Example

📄 app.component.ts

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

@Component({
selector: 'app-root',
template: `<h2>Hello from App Component!</h2>`
})
export class AppComponent {}

Here, <app-root> is a component directive used in index.html.

✅ 2. Structural Directives

These change the structure of the DOM (add/remove elements).

🔹 Common Examples: *ngIf, *ngFor


🔸 Example 1 – *ngIf

📄 app.component.html

html
CopyEdit
<h2 *ngIf="show">This text is conditionally shown</h2>
<button (click)="show = !show">Toggle</button>

📄 app.component.ts

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

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

🔸 Example 2 – *ngFor
html
CopyEdit
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
ts
CopyEdit
items = ['Apple', 'Banana', 'Orange'];

✅ 3. Attribute Directives

These change the appearance or behavior of an element.

🔹 Built-in Example – ngStyle


html
CopyEdit
<p [ngStyle]="{'color': color, 'font-size': fontSize}">
Styled with ngStyle!
</p>
ts
CopyEdit
color = 'blue';
fontSize = '20px';

🔹 Custom Attribute Directive Example

📄 highlight.directive.ts

ts
CopyEdit
import { Directive, ElementRef } from '@angular/core';

@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}

📄 Usage in app.component.html

html
CopyEdit
<p appHighlight>This paragraph is highlighted</p>

📄 app.module.ts

Don't forget to declare the directive:

ts
CopyEdit
import { HighlightDirective } from './highlight.directive';

@NgModule({
declarations: [AppComponent, HighlightDirective],
...
})

11. Explain Injection Directives with an example.


✅ Answer to: What are Injection Directives in Angular?
In Angular, there is no official category called injection directives.
However, directives can use Angular's Dependency Injection
(DI) system to inject services, built-in classes like ElementRef, or
other dependencies into their constructors. This allows the directive
to interact with the DOM or use shared logic from services.
This use of DI inside a directive is sometimes referred to informally
as using injection in directives.

✅ Example:
ts
CopyEdit
import { Directive, ElementRef } from '@angular/core';

@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
📌 Explanation:
 appHighlight is a custom attribute directive.
 The directive uses dependency injection to inject
ElementRef, which gives direct access to the element it's
applied on.
 The directive then sets the element’s background color using
this injected reference.

🔚 Summary Line (great for exams):


So, while "injection directives" is not an official term, it usually
refers to Angular directives that use dependency injection to
access services or DOM elements.

Unit V

1. Single page Application


2. API
3. Web Services
4. MicroServices Architecture
5. Different types of Architecture =Pros and Cons of Microservices

You might also like