<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sriii on Medium]]></title>
        <description><![CDATA[Stories by Sriii on Medium]]></description>
        <link>https://medium.com/@srishti.srajput?source=rss-ccc6158bb7f7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ModIOUD7m2eveC3Z</url>
            <title>Stories by Sriii on Medium</title>
            <link>https://medium.com/@srishti.srajput?source=rss-ccc6158bb7f7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 03:51:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@srishti.srajput/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Gemini AI + Python]]></title>
            <link>https://medium.com/@srishti.srajput/gemini-ai-python-13858d87500f?source=rss-ccc6158bb7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/13858d87500f</guid>
            <category><![CDATA[google-gemini-api]]></category>
            <category><![CDATA[google-gemini-ai]]></category>
            <category><![CDATA[google-gemini]]></category>
            <dc:creator><![CDATA[Sriii]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 05:25:43 GMT</pubDate>
            <atom:updated>2025-08-11T05:25:43.781Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>So usually I wanted that we should learn something with interest like we play game so when I learn this I felt I like to learn this things so the reader I also want u to be interest have a pen and paper with laptop.do coding enjoy it.so I start this generally of <strong>how we can used Gemini Api</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ngwwcc8YtZIrSMXiRrh5EA.jpeg" /></figure><blockquote><strong>first of all let me explain little bit of Api</strong></blockquote><p>what is API<br><strong>API</strong> stands for <strong>Application Programming Interface</strong>. It is a set of rules and protocols that enable different software applications, systems, or devices to communicate and exchange data with each other.</p><p>Note : So we uses Gemini Api key for sending our data to them so they work on it and give the output</p><h4>So where to find the Gemini Api key that question arise in your mind let me explain you</h4><p>Step 1:Search this on web <a href="https://console.cloud.google.com/">https://console.cloud.google.com/</a></p><figure><img alt="Accesstheproject" src="https://cdn-images-1.medium.com/max/1024/1*_sDVUvbrYHVt1aMDBhwwIQ.png" /></figure><p>if we had project it will show there if not that we should create them when we click on that blue circle it open this page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*x3crMTrAs4kQ0wIqR8s0AA.png" /></figure><p>if we want the new project has been create click on blue circle new project it will open this in the screen we write the project name what we wanted in the circle u have seen I rename the name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*LFxl6wOtpM8rPzM9Jzm4BA.png" /></figure><p>when you click on create the notification has come on screen. Then we come to the first page where we are select the project click on black circle if we want to work with that Name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*r6splJ9jpWsUveDuX16Vhw.png" /></figure><p>Step 2:Click on this navigation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qvrBd0QkmTG8tFZcD5uDdA.png" /></figure><p>here we Should enable Gemini Api then they give access to work on them so click on blue circle</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*CKgNuN8uza55le_h1-qXiw.png" /></figure><p>Click on pointer that I have give on below screen to enable Gemini Api</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5kg15c-e7jvN50OdrC86A.png" /></figure><p>click on Enable APIS and services the search bar shown then search Generative Language API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*IsvBZXY2hTQvw6Hn-Sn1kw.png" /></figure><p>enable it by click on Gemini Api it will show this if</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*tXh12z3UCqK-aGtRs9f2YQ.png" /></figure><p>So i uses gemini-flash-2.5 which is limited and free<br>Step 2:Search Gemini studio click on link <a href="https://aistudio.google.com/app/welcome">Google AI Studio</a> here click on GO to Google AI Studio (I will also mark this using pointer).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KChLVQkXpWWzd4FOc_sMGA.png" /></figure><p>click on run setting that I show in below picture with blue circle</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O9mu5lpG7D3HMBxqs6rYcg.png" /></figure><p>They will show you different model which is comfortable you choose them if you pay them choose pro version I chosen the Gemini flash 2.5 for limited access here I</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJwa33AaKUChCb3603JV7A.png" /></figure><p>All set we need the API key click on Get API key .if we are first who create the API then click on create API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DoS2IQtU22cVUV0wOusFFQ.png" /></figure><p>then selected the project and create the Api</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*lT1Axv1UZhQmjCD_-BKanw.png" /></figure><p>Click the on create Api key for existing project. API key create copy it save somewhere<br>this show in dashboard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8jKQ2gPUrN9puBVqPNFlg.png" /></figure><p>All Done by Setting the project name key etc. with free limited charged</p><p>So I show u first program to get the communication with the Gemini Api.</p><p>lets see<br>So First I create the virtual environment for having the bunch of the package in one place</p><pre>python -m venv nameofvirtualenviroment</pre><p>Activate the virtual environment for download the certain package within environment.</p><pre>nameofvirtualenviroment\Scripts\Activate</pre><p>Download certain package.</p><pre>pip install google.generativeai<br>if need to upgrade the pip upgrade it</pre><pre>import google.generativeai as genai<br>key=&quot;AAAAA&quot;<br>genai.configure(api_key=key)<br>model=genai.GenerativeModel(&quot;gemini-2.5-flash&quot;)<br>prompt=&quot;Hello i love to talk to you and learn gemini api key communication using code python ?&quot;<br>res=model.generate_content(prompt)<br>print(res.text)</pre><p>Run this and it work it <br>Conclusion:We learn how to create the project and key with first program to communicate with api using python</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13858d87500f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to send the error notification by email in python]]></title>
            <link>https://medium.com/@srishti.srajput/how-to-send-the-error-notification-by-email-in-python-ba5be55895d2?source=rss-ccc6158bb7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba5be55895d2</guid>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sriii]]></dc:creator>
            <pubDate>Fri, 09 May 2025 07:35:29 GMT</pubDate>
            <atom:updated>2025-05-09T07:35:29.023Z</atom:updated>
            <content:encoded><![CDATA[<p>Implement the automated email alert for python error using smtp and login.<br>Lets see first<br>I am create the Json file to store mail information<br>mail. Json</p><pre>{<br>    &quot;smtp_server&quot;: &quot;smtp.gmail.com&quot;,<br>    &quot;smtp_port&quot;: 587,<br>    &quot;sender_email&quot;: &quot;sender_mail&quot;,<br>    &quot;sender_password&quot;: &quot;you-app-password&quot;,<br>    &quot;recipient_email&quot;: &quot;recipited_mail&quot;<br>}</pre><pre>import os<br>import smtplib<br>import json<br>import traceback<br>from file_operations import read_config<br>from excel_operations import process_excel_files<br><br>def read_mail_config():<br>    mail_config_path = os.path.join(os.path.dirname(__file__), &#39;mail.json&#39;)<br>    with open(mail_config_path, &#39;r&#39;) as file:<br>        return json.load(file)<br><br>def send_error_email(error_message):<br>    try:<br>        mail_config = read_mail_config()<br>        smtp_server = mail_config[&quot;smtp_server&quot;]<br>        smtp_port = mail_config[&quot;smtp_port&quot;]<br>        sender_email = mail_config[&quot;sender_email&quot;]<br>        sender_password = mail_config[&quot;sender_password&quot;]<br>        recipient_email = mail_config[&quot;recipient_email&quot;]<br><br>        print(f&quot;Connecting to SMTP server: {smtp_server}:{smtp_port}&quot;)<br><br>        with smtplib.SMTP(smtp_server, smtp_port) as server:<br>            server.starttls()<br>            server.login(sender_email, sender_password)<br>            email_message = f&quot;Subject: Script Error\n\n{error_message}&quot;<br>            server.sendmail(sender_email, recipient_email, email_message)<br><br>        print(&quot;Error email sent successfully.&quot;)<br><br>    except smtplib.SMTPConnectError:<br>        print(&quot;Could not connect to SMTP server. Check your internet connection.&quot;)<br>    except smtplib.SMTPAuthenticationError:<br>        print(&quot;Authentication failed. Verify your email and password.&quot;)<br>    except smtplib.SMTPException as smtp_error:<br>        print(f&quot;SMTP error: {smtp_error}&quot;)<br>    except Exception as e:<br>        print(f&quot;Unexpected error while sending email: {e}&quot;)<br><br><br>def main():<br>    try:<br>        config_path = os.path.join(os.path.dirname(__file__), &#39;config.json&#39;)<br>        config = read_config(config_path)<br>        main_folder = config[&#39;MainPath&#39;]<br>        process_excel_files(main_folder, config)<br><br>    except Exception as e:<br>        error_message = traceback.format_exc()<br>        print(f&quot;An error occurred:\n{error_message}&quot;)<br>        send_error_email(error_message)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>This is my code where we work on .xlsx file and text file<br>This script has three main tasks:</p><ol><li>Read the configuration from Json file (email settings and main config)</li><li>Process the excel files using other module(excel_operation.py)</li><li>Handle the error and if any occur sent the mail</li></ol><p>Line by Line Explanation <br>We import required package or module</p><pre>import os  # For working with file paths<br>import smtplib  # For sending emails<br>import json  # For reading JSON configuration files<br>import traceback  # For getting error details<br>from file_operations import read_config  # Import a function to read config.json<br>from excel_operations import process_excel_files  # Import a function to process Excel files</pre><ul><li>os → Helps in working with file paths.</li><li>smtplib → Handles sending emails via SMTP (Simple Mail Transfer Protocol).</li><li>json → Loads and reads JSON files.</li><li>traceback → Captures detailed error information.</li><li>file_operations.read_config → Reads the config.json file.</li><li>excel_operations.process_excel_files → Handles Excel file processing.</li></ul><p>Function to read email configuration</p><pre>def read_mail_config():<br>    mail_config_path = os.path.join(os.path.dirname(__file__), &#39;mail.json&#39;)  # Get mail.json file path<br>    with open(mail_config_path, &#39;r&#39;) as file:  # Open mail.json in read mode<br>        return json.load(file)  # Load and return JSON data</pre><p>Let’s break down the `read_mail_config()` function line by line to understand how it works and why each part is important. I’ll explain it in detail so you can learn the concepts behind it!</p><ul><li>*Function Purpose** <br>This function reads configuration data (like email credentials, SMTP server details, etc.) from a JSON file (`mail.json`) located in the same directory as your Python script. This is a common way to **securely store sensitive information** (e.g., passwords) outside your code</li></ul><pre>def read_mail_config():<br> mail_config_path = os.path.join(os.path.dirname(__file__), &#39;mail.json&#39;) # 1<br> with open(mail_config_path, &#39;r&#39;) as file: # 2<br> return json.load(file) </pre><p>1. `mail_config_path = os.path.join(…)os.path.dirname(__file__)`**: <br> — `__file__` is a built-in Python variable that represents the path of the **current script** (e.g., `”/home/user/my_script.py”`). <br> — `os.path.dirname(…)` extracts the directory part of this path (e.g., `”/home/user”`). <br>- **`os.path.join(…)`**: <br> — Combines the script’s directory path with the filename `mail.json` to create the full path to the configuration file. <br> — Example: If your script is in `C:/projects/app`, the result is `C:/projects/app/mail.json`.</p><p>**Why this matters**: <br>- Makes your code **portable**. It will work even if the script is run from a different working directory. <br>- Avoids hardcoding absolute paths (e.g., `C:\mail.json`), which can break on other machines.</p><p>#### **2. `with open(mail_config_path, ‘r’) as file:`** <br>- **`with open(…)`**: <br> — Opens the `mail.json` file in **read mode** (`’r’`). <br> — The `with` statement ensures the file is **automatically closed** after the block ends, even if an error occurs. <br>- **`as file`**: <br> — Assigns the opened file object to the variable `file`.</p><p>**Why this matters**: <br>- `with` is safer and cleaner than manually opening/closing files. <br>- Prevents resource leaks (e.g., forgetting to call `file.close()`).</p><p>3. `return json.load(file)`<br>- `json.load(file)`**: <br> — Reads the contents of `mail.json` and **parses it into a Python dictionary**. <br> — Example: If `mail.json` contains `{“user”: “admin”}`, this returns `{“user”: “admin”}`.</p><p>Why this matters: <br>- JSON is a human-readable format for storing configuration data. <br>- Easily access values like `config[“user”]` instead of parsing raw text manually.</p><p>Example `mail.json` File<br>Here’s what your JSON file might look like:<br>```json<br>{<br> “smtp_server”: “smtp.gmail.com”,<br> “smtp_port”: 465,<br> “sender_email”: “<a href="/service/mailto:your_email@gmail.com">your_email@gmail.com</a>”,<br> “sender_password”: “your_app_password”,<br> “receiver_email”: “<a href="/service/mailto:admin@example.com">admin@example.com</a>”<br>}<br>```</p><pre>### **How to Use This Function** <br>Call `read_mail_config()` to get your email settings as a dictionary:<br>```python<br>import os<br>import json<br># Assuming mail.json is in the same folder as this script<br>config = read_mail_config()<br>print(config[&quot;sender_email&quot;]) # Output: &quot;your_email@gmail.com&quot;<br>```</pre><p>Best Practices &amp; Improvements<br>1. Error Handling: Add `try/except` blocks to catch errors like: <br> — File not found (`FileNotFoundError`). <br> — Invalid JSON (`json.JSONDecodeError`).</p><pre>Example:<br> ```python<br> def read_mail_config():<br> try:<br> mail_config_path = os.path.join(os.path.dirname(__file__), &#39;mail.json&#39;)<br> with open(mail_config_path, &#39;r&#39;) as file:<br> return json.load(file)<br> except FileNotFoundError:<br> print(&quot;Error: mail.json not found!&quot;)<br> except json.JSONDecodeError:<br> print(&quot;Error: Invalid JSON format!&quot;)<br> ```</pre><p>2. Security: Never commit `mail.json` to version control (e.g., Git). Add it to `.gitignore`.</p><p>3. Environment Variables: For passwords, consider using environment variables instead of storing them in files.</p><p>Key Takeaways<br>- Use `os.path` to create **dynamic file paths** (avoids hardcoding). <br>- `with open(…)` ensures **safe file handling**. <br>- `json.load()` simplifies reading structured configuration data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba5be55895d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Floating Label Input CSS Animation]]></title>
            <link>https://medium.com/@srishti.srajput/floating-label-input-css-animation-296f5d45762c?source=rss-ccc6158bb7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/296f5d45762c</guid>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Sriii]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 08:18:13 GMT</pubDate>
            <atom:updated>2025-03-13T08:18:13.253Z</atom:updated>
            <content:encoded><![CDATA[<p>Here we see how i Design the input-field so that the label is floating correctly lets see<br>the Code of html and css<br>code</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt;<br>    &lt;title&gt;Floating Label Input&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;login&quot;&gt;<br>        &lt;div class=&quot;input-wrapper&quot;&gt;<br>            &lt;input type=&quot;text&quot; name=&quot;email&quot; id=&quot;emailid&quot; class=&quot;input-field&quot; required placeholder=&quot; &quot;&gt;<br>            &lt;label for=&quot;emailid&quot;&gt;Email Address&lt;/label&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><pre>.login {<br>    padding: 2.5rem;<br>    color: blanchedalmond;<br>}<br><br>.input-wrapper {<br>    position: relative;<br>}<br><br>.input-field {<br>    font-family: &#39;Franklin Gothic Medium&#39;, &#39;Arial Narrow&#39;, Arial, sans-serif;<br>    padding: 1rem;<br>    color: rgb(31, 28, 28);<br>    border: 2px solid black;<br>    transition: all 0.15s;<br>    background-color: transparent;<br>    outline: none;<br>    width: 100%;<br>}<br><br>.input-field:focus-visible {<br>    border-color: rgb(238, 255, 0);<br>}<br><br>.input-wrapper label {<br>    position: absolute;<br>    top: 50%;<br>    left: 20px;<br>    transform: translateY(-50%);<br>    color: rgb(29, 27, 27);<br>    transition: all 0.3s;<br>    pointer-events: none;<br>}<br><br>.input-field:focus ~ label,<br>.input-field:not(:placeholder-shown) ~ label {<br>    top: 0;<br>    left: 15px;<br>    font-size: 15px;<br>    background-color: rgb(255, 251, 251);<br>    padding: 0 5px;<br>}</pre><p>let me explain this code</p><p>here we uses different property of css like</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;</pre><ul><li>&lt;!DOCTYPE html&gt; → Declares the document as an HTML5 document.</li><li>&lt;html lang=&quot;en&quot;&gt; → Specifies that the language of the page is English.</li></ul><pre>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt;<br>    &lt;title&gt;Floating Label Input&lt;/title&gt;<br>&lt;/head&gt;</pre><ul><li>&lt;meta charset=&quot;UTF-8&quot;&gt; → Ensures the webpage supports special characters and multiple languages.</li><li>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; → Makes the website responsive by setting the viewport width to the device width.</li><li>&lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt; → Links an external CSS file (style.css) to style the webpage.</li><li>&lt;title&gt;Floating Label Input&lt;/title&gt; → Sets the title of the webpage (visible in the browser tab)</li></ul><pre>&lt;body&gt;<br>    &lt;div class=&quot;login&quot;&gt;<br>        &lt;div class=&quot;input-wrapper&quot;&gt;<br>            &lt;input type=&quot;text&quot; name=&quot;email&quot; id=&quot;emailid&quot; class=&quot;input-field&quot; required placeholder=&quot; &quot;&gt;<br>            &lt;label for=&quot;emailid&quot;&gt;Email Address&lt;/label&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><ul><li>&lt;body&gt; → Contains all the visible content of the webpage.</li><li>&lt;div class=&quot;login&quot;&gt; → A container for the input field (helps with layout and styling).</li><li>&lt;div class=&quot;input-wrapper&quot;&gt; → Another wrapper to position the label and input correctly.</li><li>&lt;input type=&quot;text&quot; name=&quot;email&quot; id=&quot;emailid&quot; class=&quot;input-field&quot; required placeholder=&quot; &quot;&gt;</li><li>type=&quot;text&quot; → Defines a text input field.</li><li>name=&quot;email&quot; → Sets the field name for form submission.</li><li>id=&quot;emailid&quot; → Provides a unique identifier for the input.</li><li>class=&quot;input-field&quot; → Used for styling the input with CSS.</li><li>required → Ensures that the user must enter a value before submitting.</li><li>placeholder=&quot; &quot; → A trick to trigger the :placeholder-shown selector in CSS while keeping the field visually empty.</li><li>&lt;label for=&quot;emailid&quot;&gt;Email Address&lt;/label&gt; → A label that is linked to the input field via the for attribute, improving accessibility and usability.</li></ul><h3>Explanation of the CSS Code:</h3><p>The CSS file styles the floating label effect.</p><h4>1. .login - Styles the form container</h4><pre>.login {<br>    padding: 2.5rem;<br>    color: blanchedalmond;<br>}</pre><ul><li>Adds 2.5rem padding around the container.</li><li>Sets text color to blanchedalmond.</li></ul><p>2. .input-wrapper - Ensures proper positioning of elements</p><pre>.input-wrapper {<br>    position: relative;<br>}</pre><p>position: relative; → Allows absolute positioning of child elements (like the label) relative to this wrapper.</p><p>3. .input-field - Styles the text input field</p><pre>.input-field {<br>    font-family: &#39;Franklin Gothic Medium&#39;, &#39;Arial Narrow&#39;, Arial, sans-serif;<br>    padding: 1rem;<br>    color: rgb(31, 28, 28);<br>    border: 2px solid black;<br>    transition: all 0.15s;<br>    background-color: transparent;<br>    outline: none;<br>    width: 100%;<br>}</pre><ul><li>Sets the font style.</li><li>padding: 1rem; → Provides spacing inside the input field.</li><li>color: rgb(31, 28, 28); → Sets text color.</li><li>border: 2px solid black; → Adds a black border.</li><li>transition: all 0.15s; → Smooth animation effects.</li><li>background-color: transparent; → Makes the background see-through.</li><li>outline: none; → Removes the default blue outline on focus.</li><li>width: 100%; → Makes the input take full width of its container.</li></ul><p>4. .input-field:focus-visible - Changes border color on focus</p><pre>.input-field:focus-visible {<br>    border-color: rgb(238, 255, 0);<br>}</pre><p>When the user clicks inside the input, the border color changes to <strong>yellow</strong> (rgb(238, 255, 0)).</p><p>5. .input-wrapper label - Positions the floating label</p><pre>.input-wrapper label {<br>    position: absolute;<br>    top: 50%;<br>    left: 20px;<br>    transform: translateY(-50%);<br>    color: rgb(29, 27, 27);<br>    transition: all 0.3s;<br>    pointer-events: none;<br>}</pre><ul><li>position: absolute; → Positions the label inside the .input-wrapper.</li><li>top: 50%; left: 20px; → Centers the label inside the input field.</li><li>transform: translateY(-50%); → Fixes vertical alignment.</li><li>color: rgb(29, 27, 27); → Sets the label text color.</li><li>transition: all 0.3s; → Animates the label when it moves.</li><li>pointer-events: none; → Prevents the label from being clicked</li></ul><p>6. .input-field:focus ~ label, .input-field:not(:placeholder-shown) ~ label - Moves the label up</p><pre>.input-field:focus ~ label,<br>.input-field:not(:placeholder-shown) ~ label {<br>    top: 0;<br>    left: 15px;<br>    font-size: 15px;<br>    background-color: rgb(255, 251, 251);<br>    padding: 0 5px;<br>}</pre><ul><li><strong>input-field:focus ~ label</strong> → When the input is clicked, the label moves up.</li><li><strong>input-field:not(:placeholder-shown) ~ label</strong> → When the user types something, the label stays up.</li><li>Moves the label to <strong>top: 0px</strong> and <strong>left: 15px</strong>.</li><li>Reduces the font size to 15px for a floating effect.</li><li>Adds a small background (rgb(255, 251, 251), light gray) behind the label.</li><li>Adds padding to the label (0 5px) to make it readable.</li></ul><h3>How the Floating Label Works?</h3><ol><li>Initially, the label is inside the input field (top: 50%).</li><li>When the input is clicked (:focus), or when text is entered (:not(:placeholder-shown)):</li></ol><ul><li>The label moves to the <strong>top</strong> (top: 0).</li><li>The font size decreases.</li><li>A background color is applied to make it readable.</li></ul><p>This creates the smooth <strong>floating label effect</strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=296f5d45762c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Forms|Template form in Angular]]></title>
            <link>https://medium.com/@srishti.srajput/reactive-forms-template-form-in-angular-118aa6e066dd?source=rss-ccc6158bb7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/118aa6e066dd</guid>
            <category><![CDATA[http-protocol]]></category>
            <category><![CDATA[custom-validation]]></category>
            <category><![CDATA[templatedriveform]]></category>
            <category><![CDATA[reactive-form-validation]]></category>
            <dc:creator><![CDATA[Sriii]]></dc:creator>
            <pubDate>Fri, 14 Feb 2025 09:51:19 GMT</pubDate>
            <atom:updated>2025-02-14T11:21:03.929Z</atom:updated>
            <content:encoded><![CDATA[<p>Reactive Form and template driven form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*CnKOsj_B8IbhY56QT6HuGw.jpeg" /></figure><h3>Reactive form</h3><p>in angular we have a reactive forms whre we add in import statement {ReactiveFormModule,FormModule,CommanModule}in .ts file then create the variable for formGroup in ts file like this</p><pre>ContactForm!:FormGroup;</pre><blockquote>Question 1. Arries what is the meaning of !(Exclamation mark) which is called as a non null assertion operator.it will tell typescript compliler the value or property or variable can not be null or undefined.</blockquote><blockquote>FormGroup:it is class that manage each FormControl in reactive form.the different form control manage by form group. It is used to manage the collection of form like (FormControl,FormArray) as a single unit</blockquote><p>Important point</p><ol><li>It track the value ,validation status,interactive state (touch,dirty) of the group as a whole</li><li>Provide the methods of add ,remove update in form control organize them correctly with doing such operation</li></ol><p>3.Allows you to set validation rules for the entire group.</p><p>How does Form Group Work lets See</p><p>We can create the form group by creating the group of form control.Each control is typically the instances of FormControl or another FormGroup</p><p>Question Arries how to create the form Group with Form control lets see first initilize the formGroup:</p><p>then Define the Form Control inside the constructor always:</p><pre>ContactForm!:FormGroup;<br>Constructor(){<br> this.ContactForm=new FormGroup({<br>name:new FormControl(&#39;&#39;),<br>Age:new FormControl(&#39;&#39;),<br>)};<br>}<br>import { FormGroup, FormControl } from &#39;@angular/forms&#39;;<br><br>this.contactForm = new FormGroup({<br>  name: new FormControl(&#39;&#39;), // A single form control<br>  email: new FormControl(&#39;&#39;), // Another form control<br>  address: new FormGroup({ // Nested FormGroup<br>    street: new FormControl(&#39;&#39;),<br>    city: new FormControl(&#39;&#39;),<br>  }),<br>});</pre><p>this is other example of Define the Group Form</p><pre>import { CommonModule } from &#39;@angular/common&#39;;<br>import { Component } from &#39;@angular/core&#39;;<br>import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from &#39;@angular/forms&#39;;<br><br>@Component({<br>  selector: &#39;app-form-studing&#39;,<br>  standalone: true,<br>  imports: [ReactiveFormsModule, FormsModule, CommonModule],<br>  templateUrl: &#39;./form-studing.component.html&#39;,<br>  styleUrls: [&#39;./form-studing.component.scss&#39;] // Corrected `styleUrl` to `styleUrls`<br>})<br>export class FormStudingComponent {<br>  ContactForm!: FormGroup;<br><br>  constructor() {<br>    this.ContactForm = new FormGroup({<br>      name: new FormControl(&#39;&#39;),<br>      DOB: new FormControl(&#39;&#39;),<br>      Age: new FormControl(&#39;&#39;)<br>    });<br>  }<br>}</pre><p>if this issues arries</p><p>Yes, there are a few issues in your code:</p><h3>Issues:</h3><p><strong>1.Incorrect usage of </strong><strong>this.ContactForm</strong></p><p>2.You are trying to assign this.ContactForm = new FormGroup(...) <strong>outside</strong> the constructor, which is not allowed.</p><p><strong>3.Incorrect usage of </strong><strong>FormControl </strong>FormControl should be instantiated with new FormControl() inside the FormGroup.</p><h3>Corrected Code:</h3><pre>import { CommonModule } from &#39;@angular/common&#39;;<br>import { Component } from &#39;@angular/core&#39;;<br>import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from &#39;@angular/forms&#39;;</pre><pre>@Component({<br>  selector: &#39;app-form-studing&#39;,<br>  standalone: true,<br>  imports: [ReactiveFormsModule, FormsModule, CommonModule],<br>  templateUrl: &#39;./form-studing.component.html&#39;,<br>  styleUrls: [&#39;./form-studing.component.scss&#39;] // Corrected `styleUrl` to `styleUrls`<br>})<br>export class FormStudingComponent {<br>  ContactForm!: FormGroup;</pre><pre>  constructor() {<br>    this.ContactForm = new FormGroup({<br>      name: new FormControl(&#39;&#39;),<br>      DOB: new FormControl(&#39;&#39;),<br>      Age: new FormControl(&#39;&#39;)<br>    });<br>  }<br>}</pre><h3>Fixes:</h3><ol><li><strong>Moved </strong><strong>this.ContactForm = new FormGroup(...) inside the constructor</strong> ✅</li><li><strong>Fixed incorrect instantiation of </strong><strong>FormControl (added </strong><strong>new keyword)</strong> ✅</li><li><strong>Fixed </strong><strong>styleUrl to </strong><strong>styleUrls (as it expects an array)</strong> ✅</li></ol><p>Now, your component should work without errors! 🚀</p><p>Qustion 3 How can we access the control in form group using get methods.</p><p>Define the varible as any or any data type in angular</p><pre>import { CommonModule } from &#39;@angular/common&#39;;<br>import { Component } from &#39;@angular/core&#39;;<br>import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from &#39;@angular/forms&#39;;<br><br>@Component({<br>  selector: &#39;app-form-studing&#39;,<br>  standalone: true,<br>  imports: [ReactiveFormsModule, FormsModule, CommonModule],<br>  templateUrl: &#39;./form-studing.component.html&#39;,<br>  styleUrls: [&#39;./form-studing.component.scss&#39;] // Fixed `styleUrl` to `styleUrls`<br>})<br>export class FormStudingComponent {<br>  ContactForm!: FormGroup;<br>  name1: any; // Corrected declaration (removed `const`)<br><br>  constructor() {<br>    this.ContactForm = new FormGroup({<br>      name: new FormControl(&#39;&#39;),<br>      DOB: new FormControl(&#39;&#39;),<br>      Age: new FormControl(&#39;&#39;)<br>    });<br><br>    this.name1 = this.ContactForm.get(&#39;name&#39;); // Moved inside the constructor to avoid undefined issues<br>  }<br>}</pre><p>Question Arries what is diffrences between ngoninit and contructor in angular</p><h3>Difference Between ngOnInit() and Constructor in Angular 🚀</h3><p>Both ngOnInit() and the <strong>constructor</strong> are part of Angular&#39;s component lifecycle, but they serve different purposes.</p><h3>1️⃣ Constructor (constructor())</h3><h3>What is it?</h3><p>The constructor is a special method in TypeScript that gets executed <strong>when a class is instantiated</strong>. In an Angular component, the constructor is used <strong>for dependency injection</strong> and initial class setup.</p><h3>Key Points:</h3><ul><li><strong>Runs first</strong> when the component is created.</li><li>Used for <strong>initializing class properties</strong>.</li><li>Used for <strong>dependency injection</strong> (e.g., injecting services).</li><li><strong>Cannot access bindings (</strong><strong>@Input())</strong> because Angular has not yet initialized them.</li></ul><h3>Example:</h3><pre>constructor(private myService: MyService) {<br>  console.log(&quot;Constructor called!&quot;); // ✅ This runs first<br>}</pre><h3>2️⃣ ngOnInit()</h3><h3>What is it?</h3><p>ngOnInit() is a lifecycle hook in Angular that gets called <strong>after Angular has initialized all data-bound properties (</strong><strong>@Input())</strong>.</p><h3>Key Points:</h3><ul><li>Called <strong>after the constructor</strong>.</li><li>Used for <strong>fetching data</strong>, <strong>API calls</strong>, or <strong>processing inputs</strong>.</li><li>Ensures that @Input() properties are available.</li><li>Recommended for <strong>component initialization logic</strong>.</li></ul><h3>Example:</h3><pre>ngOnInit() {<br>  console.log(&quot;ngOnInit called!&quot;); // ✅ This runs after constructor<br>}</pre><h3>3️⃣ When to Use Which?</h3><p>Feature Constructor ngOnInit() <strong>Called when?</strong> When the component is created After the component is initialized <strong>Can access </strong><strong>@Input()?</strong> ❌ No ✅ Yes <strong>Used for dependency injection?</strong> ✅ Yes ❌ No <strong>Used for API calls?</strong> ❌ No ✅ Yes <strong>Runs before template rendering?</strong> ✅ Yes ✅ Yes <strong>Best for?</strong> Setting up <strong>basic properties</strong>, injecting services Initializing data, fetching API data, processing @Input() values</p><h3>4️⃣ Example Use Case</h3><pre>import { Component, Input, OnInit } from &#39;@angular/core&#39;;</pre><pre>@Component({<br>  selector: &#39;app-demo&#39;,<br>  template: `&lt;p&gt;{{ message }}&lt;/p&gt;`<br>})<br>export class DemoComponent implements OnInit {<br>  @Input() data!: string;  // Input property from parent<br>  message!: string;</pre><pre>  constructor() {<br>    console.log(&quot;Constructor: Cannot access @Input() data yet&quot;);<br>  }</pre><pre>  ngOnInit() {<br>    this.message = `Data received: ${this.data}`;  // ✅ Now @Input() is available<br>    console.log(&quot;ngOnInit: Now I can access @Input() data&quot;);<br>  }<br>}</pre><h3>Output:</h3><pre>Constructor: Cannot access @Input() data yet<br>ngOnInit: Now I can access @Input() data</pre><h3>Conclusion:</h3><ul><li><strong>Use the constructor</strong> for <strong>dependency injection</strong> and class-level initializations.</li><li><strong>Use </strong><strong>ngOnInit()</strong> for <strong>fetching data, API calls, and handling </strong><strong>@Input() properties</strong>.</li></ul><p>Hope this helps! 🚀💡 Let me know if you have any questions! 😊</p><p>This is all about Reactive Form</p><h3>Form Validation in Reactive Forms (Angular)</h3><p>In <strong>Reactive Forms</strong>, validation is handled using <strong>form control classes</strong> rather than directives like in template-driven forms. Validators are applied to FormControl and FormGroup objects.</p><h3>1. Setting Up a Reactive Form with Validation</h3><p>To use <strong>Reactive Forms</strong>, you need to:</p><ol><li>Import the required modules.</li><li>Create a form using FormGroup and FormControl.</li><li>Apply validation rules.</li><li>Display validation messages in the template.</li></ol><h3>Step 1: Import Required Modules</h3><p>Modify app.module.ts (only if using a non-standalone component):</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { ReactiveFormsModule } from &#39;@angular/forms&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { AppComponent } from &#39;./app.component&#39;;</pre><pre>@NgModule({<br>  declarations: [AppComponent],<br>  imports: [BrowserModule, ReactiveFormsModule], // Import ReactiveFormsModule<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule { }</pre><blockquote><em>✅ If you are using a </em><strong><em>standalone component</em></strong><em>, you need to import </em><em>ReactiveFormsModule inside the </em><em>imports array of </em><em>@Component().</em></blockquote><h3>Step 2: Create a Form with Validation</h3><p>Inside your component (app.component.ts):</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { FormControl, FormGroup, Validators } from &#39;@angular/forms&#39;;</pre><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;]<br>})<br>export class AppComponent {<br>  contactForm: FormGroup;</pre><pre>  constructor() {<br>    this.contactForm = new FormGroup({<br>      name: new FormControl(&#39;&#39;, [Validators.required, Validators.minLength(3)]),<br>      email: new FormControl(&#39;&#39;, [Validators.required, Validators.email]),<br>      age: new FormControl(&#39;&#39;, [Validators.required, Validators.min(18), Validators.max(60)])<br>    });<br>  }</pre><pre>  onSubmit() {<br>    if (this.contactForm.valid) {<br>      console.log(&#39;Form Data:&#39;, this.contactForm.value);<br>    } else {<br>      console.log(&#39;Form is invalid&#39;);<br>    }<br>  }<br>}</pre><h3>Step 3: Display the Form with Validation Messages</h3><p>Modify app.component.html:</p><pre>&lt;form [formGroup]=&quot;contactForm&quot; (ngSubmit)=&quot;onSubmit()&quot;&gt;<br>  &lt;!-- Name Field --&gt;<br>  &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;<br>  &lt;input id=&quot;name&quot; type=&quot;text&quot; formControlName=&quot;name&quot; /&gt;<br>  &lt;div *ngIf=&quot;contactForm.get(&#39;name&#39;)?.invalid &amp;&amp; contactForm.get(&#39;name&#39;)?.touched&quot;&gt;<br>    &lt;small *ngIf=&quot;contactForm.get(&#39;name&#39;)?.errors?.[&#39;required&#39;]&quot;&gt;Name is required.&lt;/small&gt;<br>    &lt;small *ngIf=&quot;contactForm.get(&#39;name&#39;)?.errors?.[&#39;minlength&#39;]&quot;&gt;Name must be at least 3 characters.&lt;/small&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;!-- Email Field --&gt;<br>  &lt;label for=&quot;email&quot;&gt;Email:&lt;/label&gt;<br>  &lt;input id=&quot;email&quot; type=&quot;email&quot; formControlName=&quot;email&quot; /&gt;<br>  &lt;div *ngIf=&quot;contactForm.get(&#39;email&#39;)?.invalid &amp;&amp; contactForm.get(&#39;email&#39;)?.touched&quot;&gt;<br>    &lt;small *ngIf=&quot;contactForm.get(&#39;email&#39;)?.errors?.[&#39;required&#39;]&quot;&gt;Email is required.&lt;/small&gt;<br>    &lt;small *ngIf=&quot;contactForm.get(&#39;email&#39;)?.errors?.[&#39;email&#39;]&quot;&gt;Enter a valid email.&lt;/small&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;!-- Age Field --&gt;<br>  &lt;label for=&quot;age&quot;&gt;Age:&lt;/label&gt;<br>  &lt;input id=&quot;age&quot; type=&quot;number&quot; formControlName=&quot;age&quot; /&gt;<br>  &lt;div *ngIf=&quot;contactForm.get(&#39;age&#39;)?.invalid &amp;&amp; contactForm.get(&#39;age&#39;)?.touched&quot;&gt;<br>    &lt;small *ngIf=&quot;contactForm.get(&#39;age&#39;)?.errors?.[&#39;required&#39;]&quot;&gt;Age is required.&lt;/small&gt;<br>    &lt;small *ngIf=&quot;contactForm.get(&#39;age&#39;)?.errors?.[&#39;min&#39;]&quot;&gt;Age must be at least 18.&lt;/small&gt;<br>    &lt;small *ngIf=&quot;contactForm.get(&#39;age&#39;)?.errors?.[&#39;max&#39;]&quot;&gt;Age cannot be more than 60.&lt;/small&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;button type=&quot;submit&quot; [disabled]=&quot;contactForm.invalid&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;</pre><h3>Built-in Validators in Angular</h3><p>Validator Description Validators.required Field must not be empty. Validators.email Validates email format. Validators.min(n) Minimum numeric value. Validators.max(n) Maximum numeric value. Validators.minLength(n) Minimum length for strings. Validators.maxLength(n) Maximum length for strings. Validators.pattern(&#39;regex&#39;) Validates against a regex pattern.</p><h3>Custom Validator Example</h3><p>You can also create <strong>custom validators</strong>:</p><pre>import { AbstractControl, ValidationErrors } from &#39;@angular/forms&#39;;</pre><pre>export function noSpaceValidator(control: AbstractControl): ValidationErrors | null {<br>  if (control.value.includes(&#39; &#39;)) {<br>    return { noSpaces: true };<br>  }<br>  return null;<br>}</pre><p>Usage in FormControl:</p><pre>username: new FormControl(&#39;&#39;, [Validators.required, noSpaceValidator])</pre><h3>Final Notes</h3><p>✅ <strong>Advantages of Reactive Forms:</strong></p><ul><li>More scalable and testable than template-driven forms.</li><li>Works well with complex forms.</li><li>Easier state management.</li></ul><p>With this setup, your Angular <strong>Reactive Form</strong> now has <strong>validations</strong> with <strong>error handling</strong>! 🚀 Let me know if you need further explanations! 😊</p><h3>lets see the Custom validation how we create that</h3><p>Custom Creation uses tow package ValidationErrors,AbstractControl also create the function export them to uses every where as a validated custom</p><p>like this</p><blockquote>import{AbstractControl,ValidationErrors} from ‘./angular-forms’</blockquote><blockquote>export function agevalidator(Control:AbstractControl):ValidationErrors|null{const age=control.value as any if (!(age&gt;18 &amp;&amp; age&lt;50)){ return{agenot:true}}else return null }}</blockquote><h3>Creating a Custom Validator in Angular (Easy Explanation)</h3><p>A <strong>custom validator</strong> in Angular is a function that checks whether a form field meets a specific condition and returns an error if it does not.</p><h3>1. Understanding AbstractControl &amp; ValidationErrors</h3><h3>What is AbstractControl?</h3><ul><li>AbstractControl is the <strong>base class</strong> for all form controls (FormControl, FormGroup, FormArray).</li><li>It provides access to <strong>form values, validation status, and errors</strong>.</li><li>When a validator function runs, AbstractControl represents the <strong>form field (control)</strong> it&#39;s applied to.</li></ul><h3>What is ValidationErrors?</h3><ul><li>ValidationErrors is just an <strong>object</strong> (like a dictionary) that stores error messages.</li><li>If validation <strong>fails</strong>, it returns an object { errorName: true }.</li><li>If validation <strong>passes</strong>, it returns null.</li></ul><h3>2. Steps to Create a Custom Validator</h3><p>Let’s say we want a validator that <strong>does not allow spaces in the input</strong>.</p><h3>Step 1: Create the Validator Function</h3><p>Create a new file <strong>custom-validators.ts</strong> (recommended for organizing validators):</p><pre>import { AbstractControl, ValidationErrors } from &#39;@angular/forms&#39;;</pre><pre>export function noSpaceValidator(control: AbstractControl): ValidationErrors | null {<br>  // Get the value of the input field<br>  const value = control.value as string;</pre><pre>  // If value contains spaces, return an error object<br>  if (value.includes(&#39; &#39;)) {<br>    return { noSpaces: true }; // Error<br>  }</pre><pre>  return null; // Validation passed (no error)<br>}</pre><h3>Step 2: Apply the Validator to a FormControl</h3><p>Now, use this validator inside your component:</p><h4>app.component.ts</h4><pre>import { Component } from &#39;@angular/core&#39;;<br>import { FormControl, FormGroup, Validators } from &#39;@angular/forms&#39;;<br>import { noSpaceValidator } from &#39;./custom-validators&#39;; // Import the validator</pre><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;]<br>})<br>export class AppComponent {<br>  contactForm = new FormGroup({<br>    username: new FormControl(&#39;&#39;, [Validators.required, noSpaceValidator]), // Applying the custom validator<br>  });</pre><pre>  onSubmit() {<br>    console.log(this.contactForm.value);<br>  }<br>}</pre><h3>Step 3: Show Error Messages in HTML</h3><p>Modify <strong>app.component.html</strong> to display validation messages:</p><pre>&lt;form [formGroup]=&quot;contactForm&quot; (ngSubmit)=&quot;onSubmit()&quot;&gt;<br>  &lt;label for=&quot;username&quot;&gt;Username:&lt;/label&gt;<br>  &lt;input id=&quot;username&quot; type=&quot;text&quot; formControlName=&quot;username&quot; /&gt;</pre><pre>  &lt;!-- Error message --&gt;<br>  &lt;div *ngIf=&quot;contactForm.get(&#39;username&#39;)?.errors?.[&#39;noSpaces&#39;] &amp;&amp; contactForm.get(&#39;username&#39;)?.touched&quot;&gt;<br>    &lt;small&gt;No spaces allowed in username.&lt;/small&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;button type=&quot;submit&quot; [disabled]=&quot;contactForm.invalid&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;</pre><h3>3. How AbstractControl Works Here</h3><p>When the form runs validation:</p><ol><li>AbstractControl represents the <strong>current input field</strong> (e.g., username).</li><li>It passes the <strong>current input value</strong> to noSpaceValidator().</li><li>If spaces exist, ValidationErrors returns { noSpaces: true }, triggering an error message.</li><li>If no spaces, it returns null, meaning no error.</li></ol><h3>4. Example: Custom Email Validator</h3><p>Now, let’s create another custom validator that ensures <strong>emails must end with “@example.com”</strong>.</p><h3>Validator Function (custom-validators.ts)</h3><pre>export function emailDomainValidator(control: AbstractControl): ValidationErrors | null {<br>  const email = control.value as string;<br>  if (email &amp;&amp; !email.endsWith(&#39;@example.com&#39;)) {<br>    return { invalidDomain: true }; // Error<br>  }<br>  return null; // Validation passed<br>}</pre><h3>Use in FormControl (app.component.ts)</h3><pre>email: new FormControl(&#39;&#39;, [Validators.required, Validators.email, emailDomainValidator])</pre><h3>Error Message in HTML (app.component.html)</h3><pre>&lt;div *ngIf=&quot;contactForm.get(&#39;email&#39;)?.errors?.[&#39;invalidDomain&#39;]&quot;&gt;<br>  &lt;small&gt;Email must end with &quot;@example.com&quot;.&lt;/small&gt;<br>&lt;/div&gt;</pre><h3>5. Summary (Key Takeaways)</h3><p>✅ AbstractControl <strong>represents the current input field</strong> (i.e., FormControl).<br> ✅ ValidationErrors <strong>returns an error object (</strong><strong>{ errorName: true }) if validation fails</strong>.<br> ✅ Custom validators <strong>are just functions that return </strong><strong>null (valid) or an error object (invalid)</strong>.<br> ✅ <strong>To use them</strong>, apply them to FormControl like built-in validators.</p><p>Now, you can <strong>create any custom validator</strong> easily! 🚀 Let me know if anything is unclear! 😊</p><h3>Applying Age Validation and Regex in Angular Reactive Forms</h3><p>To enforce <strong>age validation</strong> and <strong>regex patterns</strong>, we use <strong>custom validators</strong> in Angular.</p><h3>1. Age Validation (Custom Validator)</h3><p>Let’s say we want to ensure that the <strong>age is between 18 and 60</strong>.</p><h3>Step 1: Create a Custom Validator</h3><p>Create a file called <strong>custom-validators.ts</strong>:</p><pre>import { AbstractControl, ValidationErrors } from &#39;@angular/forms&#39;;</pre><pre>export function ageValidator(control: AbstractControl): ValidationErrors | null {<br>  const age = control.value as number;</pre><pre>  if (age &lt; 18 || age &gt; 60) {<br>    return { invalidAge: true }; // Error if not in range<br>  }</pre><pre>  return null; // Valid age<br>}</pre><h3>Step 2: Apply Age Validator to FormControl</h3><p>Modify <strong>app.component.ts</strong>:</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { FormControl, FormGroup, Validators } from &#39;@angular/forms&#39;;<br>import { ageValidator } from &#39;./custom-validators&#39;; // Import custom validator</pre><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;]<br>})<br>export class AppComponent {<br>  contactForm = new FormGroup({<br>    age: new FormControl(&#39;&#39;, [Validators.required, ageValidator]), // Applying custom validator<br>  });</pre><pre>  onSubmit() {<br>    console.log(this.contactForm.value);<br>  }<br>}</pre><h3>Step 3: Display Error Message in HTML</h3><p>Modify <strong>app.component.html</strong>:</p><pre>&lt;form [formGroup]=&quot;contactForm&quot; (ngSubmit)=&quot;onSubmit()&quot;&gt;<br>  &lt;label for=&quot;age&quot;&gt;Age:&lt;/label&gt;<br>  &lt;input id=&quot;age&quot; type=&quot;number&quot; formControlName=&quot;age&quot; /&gt;</pre><pre>  &lt;!-- Age validation error message --&gt;<br>  &lt;div *ngIf=&quot;contactForm.get(&#39;age&#39;)?.errors?.[&#39;invalidAge&#39;] &amp;&amp; contactForm.get(&#39;age&#39;)?.touched&quot;&gt;<br>    &lt;small&gt;Age must be between 18 and 60.&lt;/small&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;button type=&quot;submit&quot; [disabled]=&quot;contactForm.invalid&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;</pre><h3>2. Regex Validation (Custom Validator for Name)</h3><p>Let’s say we want to enforce that <strong>names should contain only alphabets</strong> (no numbers or special characters).</p><h3>Step 1: Create Regex Validator</h3><p>Modify <strong>custom-validators.ts</strong>:</p><pre>export function nameValidator(control: AbstractControl): ValidationErrors | null {<br>  const regex = /^[A-Za-z\s]+$/; // Allows only letters and spaces<br>  if (!regex.test(control.value)) {<br>    return { invalidName: true }; // Error if not matching regex<br>  }<br>  return null; // Valid name<br>}</pre><h3>Step 2: Apply Regex Validator in FormControl</h3><p>Modify <strong>app.component.ts</strong>:</p><pre>import { nameValidator } from &#39;./custom-validators&#39;; // Import the validator</pre><pre>contactForm = new FormGroup({<br>  name: new FormControl(&#39;&#39;, [Validators.required, nameValidator]), // Applying custom validator<br>});</pre><h3>Step 3: Display Error Message in HTML</h3><p>Modify <strong>app.component.html</strong>:</p><pre>&lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;<br>&lt;input id=&quot;name&quot; type=&quot;text&quot; formControlName=&quot;name&quot; /&gt;</pre><pre>&lt;!-- Name validation error --&gt;<br>&lt;div *ngIf=&quot;contactForm.get(&#39;name&#39;)?.errors?.[&#39;invalidName&#39;] &amp;&amp; contactForm.get(&#39;name&#39;)?.touched&quot;&gt;<br>  &lt;small&gt;Only letters and spaces are allowed.&lt;/small&gt;<br>&lt;/div&gt;</pre><h3>3. Summary</h3><p>✅ <strong>Age Validator</strong> ensures the age is between <strong>18–60</strong>.<br> ✅ <strong>Regex Validator</strong> checks if the name contains <strong>only alphabets</strong>.<br> ✅ Both validators are <strong>reusable</strong> and can be applied to any form control.</p><p>Now, you can apply <strong>age validation and regex validation</strong> in Angular forms! 🚀 Let me know if you need any modifications. 😊</p><p>how we uses api</p><h3>Sending Form Data to API in Angular (Reactive Forms + HTTP Client)</h3><p>Now that you have learned <strong>form validation</strong> and <strong>ngSubmit</strong>, let’s move to the next step: <strong>sending form data to an API</strong>.</p><h3>1. Steps to Send Data to API</h3><ol><li><strong>Import HttpClientModule</strong> in app.module.ts.</li><li><strong>Create a service</strong> to handle API calls.</li><li><strong>Inject the service</strong> in the component.</li><li><strong>Send form data</strong> using HttpClient in ngSubmit.</li></ol><h3>2. Import HttpClientModule</h3><p>First, enable HTTP client functionality in <strong>app.module.ts</strong>:</p><pre>import { HttpClientModule } from &#39;@angular/common/http&#39;;<br>import { NgModule } from &#39;@angular/core&#39;;</pre><pre>@NgModule({<br>  imports: [HttpClientModule], // Import HttpClientModule<br>})<br>export class AppModule {}</pre><h3>3. Create an API Service</h3><p>Now, create a service file: <strong>api.service.ts</strong>.</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Observable } from &#39;rxjs&#39;;</pre><pre>@Injectable({<br>  providedIn: &#39;root&#39;, // Available throughout the app<br>})<br>export class ApiService {<br>  private apiUrl = &#39;https://jsonplaceholder.typicode.com/posts&#39;; // Fake API</pre><pre>  constructor(private http: HttpClient) {}</pre><pre>  // Method to send form data to API<br>  sendFormData(data: any): Observable&lt;any&gt; {<br>    return this.http.post(this.apiUrl, data); // Sending data via POST<br>  }<br>}</pre><h3>4. Modify the Component to Send Form Data</h3><p>Now, update <strong>app.component.ts</strong> to use the API service.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { FormControl, FormGroup, Validators } from &#39;@angular/forms&#39;;<br>import { ApiService } from &#39;./api.service&#39;; // Import API service</pre><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;]<br>})<br>export class AppComponent {<br>  contactForm = new FormGroup({<br>    name: new FormControl(&#39;&#39;, [Validators.required]),<br>    email: new FormControl(&#39;&#39;, [Validators.required, Validators.email]),<br>    age: new FormControl(&#39;&#39;, [Validators.required, Validators.min(18), Validators.max(60)]),<br>  });</pre><pre>  constructor(private apiService: ApiService) {}</pre><pre>  onSubmit() {<br>    if (this.contactForm.valid) {<br>      this.apiService.sendFormData(this.contactForm.value).subscribe({<br>        next: (response) =&gt; console.log(&#39;Success:&#39;, response),<br>        error: (error) =&gt; console.error(&#39;Error:&#39;, error)<br>      });<br>    } else {<br>      console.log(&#39;Form is invalid&#39;);<br>    }<br>  }<br>}</pre><h3>5. Modify the HTML to Trigger API Call</h3><p>Now, update <strong>app.component.html</strong>:</p><pre>&lt;form [formGroup]=&quot;contactForm&quot; (ngSubmit)=&quot;onSubmit()&quot;&gt;<br>  &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;<br>  &lt;input id=&quot;name&quot; type=&quot;text&quot; formControlName=&quot;name&quot; /&gt;<br>  &lt;div *ngIf=&quot;contactForm.get(&#39;name&#39;)?.invalid &amp;&amp; contactForm.get(&#39;name&#39;)?.touched&quot;&gt;<br>    &lt;small&gt;Name is required.&lt;/small&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;label for=&quot;email&quot;&gt;Email:&lt;/label&gt;<br>  &lt;input id=&quot;email&quot; type=&quot;email&quot; formControlName=&quot;email&quot; /&gt;<br>  &lt;div *ngIf=&quot;contactForm.get(&#39;email&#39;)?.invalid &amp;&amp; contactForm.get(&#39;email&#39;)?.touched&quot;&gt;<br>    &lt;small&gt;Enter a valid email.&lt;/small&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;label for=&quot;age&quot;&gt;Age:&lt;/label&gt;<br>  &lt;input id=&quot;age&quot; type=&quot;number&quot; formControlName=&quot;age&quot; /&gt;<br>  &lt;div *ngIf=&quot;contactForm.get(&#39;age&#39;)?.invalid &amp;&amp; contactForm.get(&#39;age&#39;)?.touched&quot;&gt;<br>    &lt;small&gt;Age must be between 18 and 60.&lt;/small&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;button type=&quot;submit&quot; [disabled]=&quot;contactForm.invalid&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;</pre><h3>6. Explanation</h3><p>✅ <strong>HttpClientModule</strong> allows API communication.<br> ✅ <strong>ApiService</strong> handles the API request.<br> ✅ <strong>ngSubmit</strong> calls onSubmit(), which checks if the form is valid before sending data.<br> ✅ <strong>this.apiService.sendFormData()</strong> sends form data via <strong>POST request</strong> to the API.<br> ✅ <strong>Observable </strong><strong>.subscribe()</strong> listens for API responses and handles success/errors.</p><h3>7. Example API Request</h3><p>When the form is submitted, the following request will be sent:</p><pre>POST https://jsonplaceholder.typicode.com/posts<br>{<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;email&quot;: &quot;john@example.com&quot;,<br>  &quot;age&quot;: 25<br>}</pre><p>If successful, the API will return a response like:</p><pre>{<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;email&quot;: &quot;john@example.com&quot;,<br>  &quot;age&quot;: 25,<br>  &quot;id&quot;: 101<br>}</pre><h3>8. Summary</h3><p>🎯 <strong>Step 1</strong>: Import HttpClientModule.<br> 🎯 <strong>Step 2</strong>: Create an API service (sendFormData()).<br> 🎯 <strong>Step 3</strong>: Inject and call the service in onSubmit().<br> 🎯 <strong>Step 4</strong>: Validate the form before sending data.</p><p>Now you can <strong>send data to an API</strong> in Angular! 🚀 Let me know if you need more details. 😊</p><h3>Template Drive form</h3><h3>Template-driven Forms in Angular (Easy Explanation) 😊</h3><p>A <strong>Template-driven form</strong> is a simple way to create forms in Angular where most of the logic is written in the <strong>HTML template</strong>, rather than in TypeScript.</p><h3>1. How Does a Template-driven Form Work?</h3><ul><li>Uses <strong>ngModel</strong> for two-way data binding.</li><li>Uses <strong>Angular directives</strong> (ngForm, required, minlength, etc.).</li><li>The <strong>entire form is controlled in the HTML file</strong> with minimal TypeScript code.</li><li>Best for <strong>simple forms</strong> (like login, contact forms).</li></ul><h3>2. Example of a Template-driven Form 🚀</h3><h3>Step 1: Import FormsModule in app.module.ts</h3><p>Before using template-driven forms, <strong>enable </strong><strong>FormsModule</strong> in app.module.ts:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { FormsModule } from &#39;@angular/forms&#39;; // ✅ Import this</pre><pre>import { AppComponent } from &#39;./app.component&#39;;</pre><pre>@NgModule({<br>  declarations: [AppComponent],<br>  imports: [BrowserModule, FormsModule], // ✅ Add FormsModule here<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule { }</pre><h3>Step 2: Create the Form in app.component.html</h3><pre>&lt;form #userForm=&quot;ngForm&quot; (ngSubmit)=&quot;onSubmit(userForm)&quot;&gt;<br>  &lt;label&gt;Name:&lt;/label&gt;<br>  &lt;input type=&quot;text&quot; name=&quot;username&quot; [(ngModel)]=&quot;user.name&quot; required&gt;<br>  <br>  &lt;label&gt;Email:&lt;/label&gt;<br>  &lt;input type=&quot;email&quot; name=&quot;email&quot; [(ngModel)]=&quot;user.email&quot; required&gt;</pre><pre>  &lt;label&gt;Age:&lt;/label&gt;<br>  &lt;input type=&quot;number&quot; name=&quot;age&quot; [(ngModel)]=&quot;user.age&quot; min=&quot;18&quot; required&gt;</pre><pre>  &lt;button type=&quot;submit&quot; [disabled]=&quot;userForm.invalid&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;</pre><p>✅ Uses ngModel to <strong>bind form fields</strong> to the user object.<br> ✅ Uses <strong>directives</strong> like required, min=&quot;18&quot; for validation.<br> ✅ The <strong>Submit button is disabled</strong> if the form is invalid.</p><h3>Step 3: Handle Form Submission in app.component.ts</h3><pre>import { Component } from &#39;@angular/core&#39;;</pre><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>})<br>export class AppComponent {<br>  user = { name: &#39;&#39;, email: &#39;&#39;, age: null };</pre><pre>  onSubmit(form: any) {<br>    console.log(&#39;Form Submitted:&#39;, form.value);<br>  }<br>}</pre><p>✅ When the form is submitted, onSubmit() logs the form values.</p><h3>3. Form Validation in Template-driven Forms</h3><p>Angular provides built-in <strong>validation</strong> like:</p><ul><li>required → Field cannot be empty</li><li>email → Must be a valid email format</li><li>minlength=&quot;5&quot; → Minimum character limit</li><li>min=&quot;18&quot; → Minimum age limit</li></ul><h3>Example: Show Validation Messages</h3><pre>&lt;form #userForm=&quot;ngForm&quot; (ngSubmit)=&quot;onSubmit(userForm)&quot;&gt;<br>  &lt;input type=&quot;text&quot; name=&quot;username&quot; [(ngModel)]=&quot;user.name&quot; required #name=&quot;ngModel&quot;&gt;<br>  &lt;div *ngIf=&quot;name.invalid &amp;&amp; name.touched&quot;&gt;Name is required&lt;/div&gt;</pre><pre>  &lt;input type=&quot;email&quot; name=&quot;email&quot; [(ngModel)]=&quot;user.email&quot; required #email=&quot;ngModel&quot;&gt;<br>  &lt;div *ngIf=&quot;email.invalid &amp;&amp; email.touched&quot;&gt;Enter a valid email&lt;/div&gt;</pre><pre>  &lt;button type=&quot;submit&quot; [disabled]=&quot;userForm.invalid&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;</pre><p>✅ Uses #name=&quot;ngModel&quot; to track form control state.<br> ✅ name.touched ensures error messages appear <strong>only after clicking the field</strong>.</p><h3>4. When Should You Use Template-driven Forms?</h3><p>✅ <strong>Good for:</strong> Simple forms like login, registration, contact forms.<br> ✅ <strong>Not recommended for:</strong> Large or dynamic forms (Use <strong>Reactive Forms</strong> instead).</p><p>Would you like an example of sending this form data to an API? 😊</p><p>Difference between template Driven and Reactive form</p><p>Yes! <strong>Template-driven forms</strong> and <strong>Reactive forms</strong> are two different approaches to handling forms in Angular. Let’s break it down in a simple way.</p><h3>1. Main Differences Between Template-driven and Reactive Forms</h3><p>Feature Template-driven Forms Reactive Forms <strong>Form Creation</strong> Created in the HTML file using directives like ngModel Created in the TypeScript file using FormGroup and FormControl <strong>Best for</strong> Simple, basic forms Complex, dynamic forms <strong>Validation Handling</strong> Uses Angular directives (required, minlength, etc.) Uses <strong>validators</strong> inside TypeScript code <strong>Two-way Data Binding</strong> Yes (ngModel) No, explicit FormControl needed <strong>Scalability</strong> Harder to manage in large applications Easier to manage and test <strong>Unit Testing</strong> Difficult Easy (logic is in TypeScript)</p><h3>2. Example of Template-driven Form (Basic Forms)</h3><p>✅ Best when the form structure is <strong>simple</strong> and doesn’t change dynamically.</p><h3>app.component.html</h3><pre>&lt;form #userForm=&quot;ngForm&quot; (ngSubmit)=&quot;onSubmit(userForm)&quot;&gt;<br>  &lt;input type=&quot;text&quot; name=&quot;username&quot; [(ngModel)]=&quot;user.name&quot; required&gt;<br>  &lt;input type=&quot;email&quot; name=&quot;email&quot; [(ngModel)]=&quot;user.email&quot; required&gt;<br>  &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;</pre><h3>app.component.ts</h3><pre>export class AppComponent {<br>  user = { name: &#39;&#39;, email: &#39;&#39; };</pre><pre>  onSubmit(form: any) {<br>    console.log(&#39;Form Submitted:&#39;, form.value);<br>  }<br>}</pre><h3>Key Points:</h3><p>✅ Uses ngModel for two-way data binding<br> ✅ ngForm handles validation automatically<br> ✅ Simple but less scalable</p><h3>3. Example of Reactive Form (For Large Forms)</h3><p>✅ Best when the form needs <strong>dynamic validation</strong>, custom validation, or handling large data.</p><h3>app.component.ts</h3><pre>import { Component } from &#39;@angular/core&#39;;<br>import { FormGroup, FormControl, Validators } from &#39;@angular/forms&#39;;</pre><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>})<br>export class AppComponent {<br>  userForm = new FormGroup({<br>    username: new FormControl(&#39;&#39;, [Validators.required, Validators.minLength(3)]),<br>    email: new FormControl(&#39;&#39;, [Validators.required, Validators.email])<br>  });</pre><pre>  onSubmit() {<br>    console.log(&#39;Reactive Form Submitted:&#39;, this.userForm.value);<br>  }<br>}</pre><h3>app.component.html</h3><pre>&lt;form [formGroup]=&quot;userForm&quot; (ngSubmit)=&quot;onSubmit()&quot;&gt;<br>  &lt;input type=&quot;text&quot; formControlName=&quot;username&quot;&gt;<br>  &lt;input type=&quot;email&quot; formControlName=&quot;email&quot;&gt;<br>  &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;</pre><h3>Key Points:</h3><p>✅ Uses FormGroup and FormControl to manage form controls<br> ✅ <strong>No </strong><strong>ngModel needed</strong>, everything is inside TypeScript<br> ✅ Easy to add <strong>custom validation</strong></p><h3>4. Which One Should You Use?</h3><ul><li>✅ <strong>Use Template-driven forms</strong> when working on small, simple forms.</li><li>✅ <strong>Use Reactive forms</strong> for complex, dynamic, or scalable forms (recommended for most real-world projects).</li></ul><p>Would you like me to show an example of <strong>custom validation</strong> in Reactive Forms? 😊</p><p>These are the form which i am create that is reactive form</p><pre>&lt;form [formGroup]=&quot;TalukaData&quot; (ngSubmit)=&quot;SubmitData()&quot;&gt;<br>    &lt;label for=&quot;Name&quot;&gt;Enter the talukaId:&lt;/label&gt;<br>    &lt;input type=&quot;text&quot; formControlName=&quot;talukaId&quot;&gt;<br>    &lt;label for=&quot;age&quot;&gt;enter the talukaName&lt;/label&gt;<br>    &lt;input type=&quot;text&quot; formControlName=&quot;talukaName&quot;&gt;<br>    &lt;label for=&quot;cityId&quot;&gt;enter the cityId&lt;/label&gt;<br>    &lt;input type=&quot;text&quot; formControlName=&quot;cityId&quot;&gt;<br>  &lt;button&gt;Submit&lt;/button&gt;<br><br><br>&lt;/form&gt;</pre><pre>import { CommonModule } from &#39;@angular/common&#39;;<br>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from &#39;@angular/forms&#39;;<br>import { Agevalidator } from &#39;./Custom-validation&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br><br><br>@Component({<br>  selector: &#39;app-form-studing&#39;,<br>  standalone: true,<br>  imports: [ReactiveFormsModule, FormsModule, CommonModule],<br>  templateUrl: &#39;./form-studing.component.html&#39;,<br>  styleUrl: &#39;./form-studing.component.scss&#39;<br>})<br>export class FormStudingComponent implements OnInit  {<br>  TalukaData!:FormGroup<br>  constructor(private http:HttpClient){}<br><br> ngOnInit(){<br>  //Called after the constructor, initializing input properties, and the first call to ngOnChanges.<br>  //Add &#39;implements OnInit&#39; to the class.<br>  this.TalukaData=new FormGroup({<br>    <br>      talukaId: new FormControl(&#39;&#39;),<br>      talukaName:new FormControl(&#39;&#39;),<br>      cityId: new FormControl(&#39;&#39;)<br>    <br>});<br>debugger;<br>  <br> }<br>SubmitData(){<br>  if(!this.TalukaData.invalid){<br>    this.http.post(&#39;https://freeapi.miniprojectideas.com/api/Annadata/AddTaluka&#39;,this.TalukaData.value);<br>    console.log(&quot;Data is Submitted&quot;)<br>   }<br>  else{<br>    console.error(&quot;error occur&quot;)<br>  }<br>} <br><br>  <br> <br>}</pre><p>Template Drive form<br>Lets see the example</p><p>ngSubmit must be like this uses name if u create the reactive or template form in html that is require name in input like this</p><pre> &lt;label&gt;Name:&lt;/label&gt;<br>    &lt;input type=&quot;text&quot; name=&quot;username&quot; [(ngModel)]=&quot;user.name&quot; required&gt; &lt;!-- ✅ Added name=&quot;username&quot; --&gt;</pre><p>ngSubmit should be like this we uses template driven for simple form</p><pre>&lt;!-- &lt;form [formGroup]=&quot;TalukaData&quot; (ngSubmit)=&quot;SubmitData()&quot;&gt;<br>    &lt;label for=&quot;Name&quot;&gt;Enter the talukaId:&lt;/label&gt;<br>    &lt;input type=&quot;text&quot; formControlName=&quot;talukaId&quot;&gt;<br>    &lt;label for=&quot;age&quot;&gt;enter the talukaName&lt;/label&gt;<br>    &lt;input type=&quot;text&quot; formControlName=&quot;talukaName&quot;&gt;<br>    &lt;label for=&quot;cityId&quot;&gt;enter the cityId&lt;/label&gt;<br>    &lt;input type=&quot;text&quot; formControlName=&quot;cityId&quot;&gt;<br>  &lt;button&gt;Submit&lt;/button&gt;<br><br><br>&lt;/form&gt; --&gt;<br>&lt;form #userForm=&quot;ngForm&quot; (ngSubmit)=&quot;SubmitData1(userForm)&quot;&gt;<br>    &lt;label&gt;Name:&lt;/label&gt;<br>    &lt;input type=&quot;text&quot; name=&quot;username&quot; [(ngModel)]=&quot;user.name&quot; required&gt; &lt;!-- ✅ Added name=&quot;username&quot; --&gt;<br>  <br>    &lt;label&gt;Email:&lt;/label&gt;<br>    &lt;input type=&quot;email&quot; name=&quot;email&quot; [(ngModel)]=&quot;user.email&quot; required&gt; &lt;!-- ✅ Added name=&quot;email&quot; --&gt;<br>  <br>    &lt;label&gt;Age:&lt;/label&gt;<br>    &lt;input type=&quot;number&quot; name=&quot;age&quot; [(ngModel)]=&quot;user.age&quot; required&gt; &lt;!-- ✅ Added name=&quot;age&quot; --&gt;<br>  <br>    &lt;button type=&quot;submit&quot; [disabled]=&quot;userForm.invalid&quot;&gt;Submit&lt;/button&gt;<br>  &lt;/form&gt;</pre><pre>import { CommonModule } from &#39;@angular/common&#39;;<br>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from &#39;@angular/forms&#39;;<br>import { Agevalidator } from &#39;./Custom-validation&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br><br><br>@Component({<br>  selector: &#39;app-form-studing&#39;,<br>  standalone: true,<br>  imports: [ReactiveFormsModule, FormsModule, CommonModule],<br>  templateUrl: &#39;./form-studing.component.html&#39;,<br>  styleUrl: &#39;./form-studing.component.scss&#39;<br>})<br>export class FormStudingComponent {<br>  // TalukaData!:FormGroup<br>  user={name:&#39;&#39;,age:&#39;&#39;,email:&#39;&#39;}<br>  constructor(private http:HttpClient){}<br><br>//  ngOnInit(){<br>//   //Called after the constructor, initializing input properties, and the first call to ngOnChanges.<br>//   //Add &#39;implements OnInit&#39; to the class.<br>//   this.TalukaData=new FormGroup({<br>    <br>//       talukaId: new FormControl(&#39;&#39;),<br>//       talukaName:new FormControl(&#39;&#39;),<br>//       cityId: new FormControl(&#39;&#39;)<br>    <br>// });<br> <br>// debugger;<br>  <br>//  }<br>// SubmitData(){<br>//   if(!this.TalukaData.invalid){<br>//     this.http.post(&#39;https://freeapi.miniprojectideas.com/api/Annadata/AddTaluka&#39;,this.TalukaData.value);<br>//     console.log(&quot;Data is Submitted&quot;)<br>//    }<br>//   else{<br>//     console.error(&quot;error occur&quot;)<br>//   }<br>// } <br>SubmitData1(userdata:any){<br>  debugger;<br>  console.log(&quot;Data Submitted&quot;,userdata.value)<br><br>}<br>  <br> <br>}</pre><h3>Why This Error Occurs?</h3><p>The error <strong>NG01352: If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as ‘standalone’</strong> happens because Angular <strong>requires a name attribute when using </strong><strong>ngModel inside a form</strong>.</p><h3>Fix the Error (Solution)</h3><p>You need to <strong>add a </strong><strong>name attribute</strong> to your input field inside the &lt;form&gt; tag.</p><h3>✅ Correct Example:</h3><pre>&lt;form #userForm=&quot;ngForm&quot;&gt;<br>  &lt;label&gt;Name:&lt;/label&gt;<br>  &lt;input type=&quot;text&quot; name=&quot;username&quot; [(ngModel)]=&quot;user.name&quot; required&gt; &lt;!-- ✅ Added name=&quot;username&quot; --&gt;</pre><pre>  &lt;label&gt;Email:&lt;/label&gt;<br>  &lt;input type=&quot;email&quot; name=&quot;email&quot; [(ngModel)]=&quot;user.email&quot; required&gt; &lt;!-- ✅ Added name=&quot;email&quot; --&gt;</pre><pre>  &lt;label&gt;Age:&lt;/label&gt;<br>  &lt;input type=&quot;number&quot; name=&quot;age&quot; [(ngModel)]=&quot;user.age&quot; required&gt; &lt;!-- ✅ Added name=&quot;age&quot; --&gt;</pre><pre>  &lt;button type=&quot;submit&quot; [disabled]=&quot;userForm.invalid&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;</pre><p>✅ Adding name=&quot;field_name&quot; fixes the issue.</p><h3>Alternative Fix Using standalone Mode</h3><p>If you don’t want to add a name attribute, set standalone: true in ngModelOptions:</p><pre>&lt;input type=&quot;text&quot; [(ngModel)]=&quot;user.name&quot; [ngModelOptions]=&quot;{standalone: true}&quot;&gt;</pre><p>✅ This tells Angular that the field is <strong>not part of the form</strong>.</p><h3>Why Does This Error Happen?</h3><ul><li>Angular’s template-driven forms use the <strong>name attribute</strong> to register controls with ngForm.</li><li>Without a name, Angular doesn&#39;t know how to track the field <strong>inside the form</strong>.</li></ul><h3>Final Notes</h3><p>✅ <strong>Use </strong><strong>name attribute</strong> when ngModel is inside a &lt;form&gt;.<br> ✅ <strong>Use </strong><strong>standalone: true</strong> when the input is <strong>not part of the form</strong>.</p><p>Let me know if you need more help! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=118aa6e066dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Http protocol: Angular 18 typescript]]></title>
            <link>https://medium.com/@srishti.srajput/http-protocol-angular-18-typescript-46e8ae9f25e2?source=rss-ccc6158bb7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/46e8ae9f25e2</guid>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Sriii]]></dc:creator>
            <pubDate>Fri, 14 Feb 2025 09:09:15 GMT</pubDate>
            <atom:updated>2025-02-14T09:09:15.018Z</atom:updated>
            <content:encoded><![CDATA[<h3>HTTP GET &amp; POST Requests with Parameters in Angular</h3><p>Angular provides <strong>HttpClient</strong> to make API calls. Let’s go through different scenarios of GET and POST requests with parameters.</p><h3>1. HTTP GET Request with Parameters</h3><h3>Example 1: Fetching User by ID</h3><p>Let’s say we have an API endpoint:</p><pre>GET https://jsonplaceholder.typicode.com/users/1</pre><p>Here’s how we make a GET request in Angular:</p><pre>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { Observable } from &#39;rxjs&#39;;</pre><pre>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class ApiService {<br>  private baseUrl = &#39;https://jsonplaceholder.typicode.com/users&#39;;</pre><pre>  constructor(private http: HttpClient) {}</pre><pre>  // GET user by ID<br>  getUserById(userId: number): Observable&lt;any&gt; {<br>    return this.http.get(`${this.baseUrl}/${userId}`);<br>  }<br>}</pre><h3>How to Call it in a Component</h3><pre>import { Component } from &#39;@angular/core&#39;;<br>import { ApiService } from &#39;./api.service&#39;;</pre><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;],<br>})<br>export class AppComponent {<br>  userData: any;</pre><pre>  constructor(private apiService: ApiService) {}</pre><pre>  fetchUser() {<br>    this.apiService.getUserById(1).subscribe((data) =&gt; {<br>      this.userData = data;<br>      console.log(&#39;User Data:&#39;, this.userData);<br>    });<br>  }<br>}</pre><h3>Calling it in HTML</h3><pre>&lt;button (click)=&quot;fetchUser()&quot;&gt;Fetch User&lt;/button&gt;<br>&lt;div *ngIf=&quot;userData&quot;&gt;<br>  &lt;p&gt;Name: {{ userData.name }}&lt;/p&gt;<br>  &lt;p&gt;Email: {{ userData.email }}&lt;/p&gt;<br>&lt;/div&gt;</pre><h3>2. HTTP GET Request with Query Parameters</h3><h3>Example 2: Fetching Users with Filters</h3><p>API Example:</p><pre>GET https://jsonplaceholder.typicode.com/users?city=London</pre><h3>Implementation</h3><pre>getUsersByCity(city: string): Observable&lt;any&gt; {<br>  return this.http.get(`${this.baseUrl}`, { params: { city: city } });<br>}</pre><h3>How to Call it</h3><pre>this.apiService.getUsersByCity(&#39;London&#39;).subscribe((data) =&gt; {<br>  console.log(&#39;Users in London:&#39;, data);<br>});</pre><h3>3. HTTP POST Request (Sending Data to API)</h3><h3>Example 3: Creating a New User</h3><p>API Example:</p><pre>POST https://jsonplaceholder.typicode.com/users<br>Body:<br>{<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;email&quot;: &quot;john@example.com&quot;<br>}</pre><h3>Implementation</h3><pre>createUser(userData: any): Observable&lt;any&gt; {<br>  return this.http.post(this.baseUrl, userData);<br>}</pre><h3>How to Call it</h3><pre>const newUser = { name: &#39;John Doe&#39;, email: &#39;john@example.com&#39; };<br>this.apiService.createUser(newUser).subscribe((response) =&gt; {<br>  console.log(&#39;User Created:&#39;, response);<br>});</pre><h3>4. HTTP PUT Request (Updating Data)</h3><h3>Example 4: Updating User</h3><p>API Example:</p><pre>PUT https://jsonplaceholder.typicode.com/users/1<br>Body:<br>{<br>  &quot;name&quot;: &quot;John Updated&quot;,<br>  &quot;email&quot;: &quot;john_updated@example.com&quot;<br>}</pre><h3>Implementation</h3><pre>updateUser(userId: number, userData: any): Observable&lt;any&gt; {<br>  return this.http.put(`${this.baseUrl}/${userId}`, userData);<br>}</pre><h3>How to Call it</h3><pre>const updatedUser = { name: &#39;John Updated&#39;, email: &#39;john_updated@example.com&#39; };<br>this.apiService.updateUser(1, updatedUser).subscribe((response) =&gt; {<br>  console.log(&#39;User Updated:&#39;, response);<br>});</pre><h3>5. HTTP DELETE Request (Deleting Data)</h3><h3>Example 5: Deleting User</h3><p>API Example:</p><pre>DELETE https://jsonplaceholder.typicode.com/users/1</pre><h3>Implementation</h3><pre>deleteUser(userId: number): Observable&lt;any&gt; {<br>  return this.http.delete(`${this.baseUrl}/${userId}`);<br>}</pre><h3>How to Call it</h3><pre>this.apiService.deleteUser(1).subscribe((response) =&gt; {<br>  console.log(&#39;User Deleted:&#39;, response);<br>});</pre><h3>6. Handling Errors using catchError</h3><pre>import { catchError } from &#39;rxjs/operators&#39;;<br>import { throwError } from &#39;rxjs&#39;;</pre><pre>getUserById(userId: number): Observable&lt;any&gt; {<br>  return this.http.get(`${this.baseUrl}/${userId}`).pipe(<br>    catchError((error) =&gt; {<br>      console.error(&#39;Error fetching user:&#39;, error);<br>      return throwError(error);<br>    })<br>  );<br>}</pre><h3>Summary</h3><p>API Type Example <strong>GET</strong> (By ID) getUserById(1) <strong>GET</strong> (With Params) getUsersByCity(&#39;London&#39;) <strong>POST</strong> (Create User) createUser({ name: &#39;John&#39; }) <strong>PUT</strong> (Update User) updateUser(1, { name: &#39;Updated&#39; }) <strong>DELETE</strong> (Delete User) deleteUser(1)</p><p>Now, you can <strong>send, update, and delete</strong> data in Angular! 🚀 Let me know if you need more help. 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46e8ae9f25e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data binding, Route in angular 18]]></title>
            <link>https://medium.com/@srishti.srajput/data-binding-route-in-angular-18-fbf28c81d7e3?source=rss-ccc6158bb7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbf28c81d7e3</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[data-binding-in-angular]]></category>
            <category><![CDATA[router]]></category>
            <dc:creator><![CDATA[Sriii]]></dc:creator>
            <pubDate>Wed, 01 Jan 2025 04:53:05 GMT</pubDate>
            <atom:updated>2025-01-01T04:53:05.939Z</atom:updated>
            <content:encoded><![CDATA[<p>Data binding is a communication between component class and view template there is a two type of binding</p><ol><li>One way binding:when we access the component class property and its corresponds view template.interpolation {{names etc}}.property binding [],event binding ()</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*qPxQocX-goT2-OYCddFkyQ.png" /></figure><figure><img alt="Event binding" src="https://cdn-images-1.medium.com/max/789/1*BvSAHlRbv-2A3Hc5sevLQw.png" /></figure><p>2.two way binding:it binds the component class to view template and to view template to component class .it is combination of property binding and event binding</p><figure><img alt="Two way binding" src="https://cdn-images-1.medium.com/max/792/1*vNIDT0R5x4GjXumeez77QQ.png" /></figure><p>Overview of Data Binding</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*4V86UT6RsLzj_-ttrhZDUQ.png" /></figure><h3>Types of Data Binding in Angular</h3><p>Angular provides **four types of data binding** that allow communication between the application’s **view** (HTML) and **model**</p><p>Let’s understand them one by one.</p><p>1. Interpolation (One-Way Data Binding: Model to View)</p><ul><li>What It Does: Displays data from the **model** (component) to the **view** (HTML).<br>- How It Works: Encloses the model property in double curly braces `{{ }}`.<br>- Example:</li></ul><pre>// app.component.ts<br> import { Component } from &#39;@angular/core&#39;;<br>@Component({<br> selector: &#39;app-root&#39;,<br> templateUrl: &#39;./app.component.html&#39;,<br> })<br> export class AppComponent {<br> message = &#39;Hello, Angular!&#39;; // Model<br> }<br> ```<br>```html<br> &lt;! - app.component.html →<br> &lt;p&gt;{{ message }}&lt;/p&gt; &lt;! - Displays: Hello, Angular! →<br> ``` **Use Case**: Displaying dynamic data in the UI.</pre><p>— -</p><p>2. **Property Binding (One-Way Data Binding: Model to View)**</p><ul><li>**What It Does**: Binds a property of an HTML element to a value in the **model** (component).<br>- **How It Works**: Uses square brackets `[]` around the property.</li></ul><pre>- **Example**:<br> ```typescript<br> // app.component.ts<br> export class AppComponent {<br> imageUrl = &#39;https://example.com/image.png&#39;; // Model<br> }<br> ```<br>```html<br> &lt;! - app.component.html →<br> &lt;img [src]=&quot;imageUrl&quot; /&gt; &lt;! - Binds the src attribute to imageUrl →</pre><p>- **Use Case**: Dynamically updating attributes like `src`, `disabled`, `class`, etc.</p><p>3. **Event Binding (One-Way Data Binding: View to Model)**</p><ul><li>**What It Does**: Passes user actions (like clicks, keypresses, etc.) from the **view** to the **model**.<br>- **How It Works**: Uses parentheses `()` around the event.<br>Example</li></ul><pre>- **Example**:<br> ```typescript<br> // app.component.ts<br> export class AppComponent {<br> onClick() {<br> alert(&#39;Button clicked!&#39;); // Model logic<br> }<br> }<br> ```<br>```html<br> &lt;! - app.component.html →<br> &lt;button (click)=&quot;onClick()&quot;&gt;Click Me&lt;/button&gt;</pre><p>- **Use Case**: Handling user interactions.</p><p>— -</p><p>4. **Two-Way Data Binding (Model ↔ View)**</p><ul><li>**What It Does**: Synchronizes the data between the **view** and **model** in both directions.<br>- **How It Works**: Combines **property binding** and **event binding** using the `[(ngModel)]` directive.<br>- **Example**:</li></ul><pre>```typescript<br> // app.component.ts<br> export class AppComponent {<br> userName = &#39;&#39;; // Model<br> }<br> ```<br>```html<br> &lt;! - app.component.html →<br> &lt;input [(ngModel)]=&quot;userName&quot; /&gt; &lt;! - Two-way binding →<br> &lt;p&gt;Your name is: {{ userName }}&lt;/p&gt;</pre><p>- **Use Case**: Interactive forms where changes in the input field update the model and vice versa.</p><p>— -</p><p>Summary of Angular Data Binding Types</p><p>| **Binding Type** | **Direction** | **Example** | **Use Case** |<br>| — — — — — — — — — — — — — — | — — — — — — — — — — — — | — — — — — — — — — — — — — | — — — — — — — — — — — — — — — — — — — — |<br>| **Interpolation** | Model → View | `{{ message }}` | Display dynamic data in the view |<br>| **Property Binding** | Model → View | `[src]=”imageUrl”` | Dynamically update element attributes |<br>| **Event Binding** | View → Model | `(click)=”onClick()”` | Handle user interactions |<br>| **Two-Way Data Binding** | Model ↔ View | `[(ngModel)]=”userName”` | Sync input fields with the model |</p><p>— -</p><p>Visual Representation</p><p>```<br>Interpolation: Model → View<br>Property Binding: Model → View<br>Event Binding: View → Model<br>Two-Way Binding: Model ←&gt; View<br>```</p><p>— -</p><p>Why is Data Binding Important?</p><p>- **Simplifies Development**: Reduces the manual effort of updating data in the view or model.<br>- **Improves Code Readability**: Makes it clear how data flows through your application.<br>- **Supports Dynamic Applications**: Essential for creating responsive and interactive web apps.</p><p>Practice these examples to solidify your understanding!</p><h3>Router In Angular</h3><p>Router are used to navigate to one application to another part or one view to other view .To handle the navigation from one view to the next, you use the Angular Router. The Router enables navigation by interpreting a browser URL as an instruction to change the view.</p><p>WildCard router:This is typically the fallback mechanism to handle the undefined or unrecoginzed router in an application</p><h3>1.Handling 404 Errors (Page Not Found)</h3><ul><li>When users navigate to a URL that doesn’t match any defined routes, the wildcard route can display a custom “404 — Page Not Found” page. This improves user experience by providing feedback about navigation errors instead of showing a blank screen or generic error message.</li></ul><pre>{ path: &#39;**&#39;, component: PageNotFoundComponent }</pre><h3>2. Redirecting to a Default Page</h3><ul><li>A wildcard route can be used to redirect users to a default or home page when they enter an unrecognized URL.</li></ul><pre>{ path: &#39;**&#39;, redirectTo: &#39;/home&#39;, pathMatch: &#39;full&#39; }</pre><h3>3. Dynamic Routing</h3><ul><li>In some applications, wildcard routes are used to capture dynamic parts of a URL that do not match predefined routes. For example, it can handle slugs or dynamic parameters.</li></ul><pre>{ path: &#39;**&#39;, component: DynamicPageComponent }</pre><h3>Key Points to Remember:</h3><ul><li>Wildcard routes should <strong>always be placed last</strong> in the route configuration because Angular (or other frameworks) processes routes sequentially.</li><li>Avoid overusing wildcard routes as they may interfere with the routing logic if placed improperly.</li><li>Combine wildcard routes with error handling and logging mechanisms to monitor frequent navigation issues in the application.</li></ul><h3>Lazy Loading Routes</h3><p>Used to load modules on demand to optimize performance.Lazy loading routes in web development is a way to <strong>improve the performance</strong> of your application by loading only the parts (or modules) of your app that are needed, when they are needed.</p><p><strong>How to use:</strong></p><ol><li>Create a module with routing.</li><li>Use loadChildren to lazy load the module.</li></ol><pre>// app-routing.module.ts<br>const routes: Routes = [<br>  { path: &#39;admin&#39;, loadChildren: () =&gt; import(&#39;./admin/admin.module&#39;).then(m =&gt; m.AdminModule) }<br>];<br>{path:&#39;databinds&#39;,loadComponent:()=&gt;import(&#39;./data-bindings-c/data-bindings-c.component&#39;).then(m=&gt;m.DataBindingsCComponent)},</pre><h3>Why Use Lazy Loading Routes?</h3><ol><li><strong>Faster Initial Load</strong>:</li></ol><p>When a user first opens your app, they only download the code for the pages they need immediately.This makes the app load faster, especially if it’s large with many features.</p><p><strong>2.Save Bandwidth</strong>:</p><p>If users don’t visit certain parts of your app, those parts won’t be downloaded at all.This is helpful for users with limited internet speeds or mobile data.</p><p><strong>3.Better User Experience</strong>:</p><p>The app feels snappy and responsive since it loads smaller chunks of code instead of the entire application at once.</p><p><strong>4.Efficient Resource Usage</strong>:</p><p>Your app uses the device’s resources (memory, processing power) more efficiently by only loading necessary code.</p><h3>Example in Angular</h3><p>Imagine you have a shopping app with two sections:</p><ul><li><strong>Home Page</strong> (for browsing products)</li><li><strong>Cart Page</strong> (for managing your shopping cart)</li></ul><p>If a user only wants to browse products, they shouldn’t need to download the code for the cart page right away.</p><h4>Without Lazy Loading</h4><p>All the code for both the Home Page and Cart Page is loaded at once, even if the user never visits the Cart Page.</p><h4>With Lazy Loading</h4><ul><li>The app only loads the Home Page code initially.</li><li>When the user clicks “Go to Cart,” the Cart Page code is downloaded at that moment.</li></ul><h3>How Lazy Loading Works</h3><p>In Angular, you set up lazy loading by creating separate modules for parts of your app and linking them with routes.</p><p>Here’s an example:</p><pre>const routes: Routes = [<br>  { path: &#39;&#39;, component: HomeComponent }, // Home Page loads immediately<br>  {<br>    path: &#39;cart&#39;,<br>    loadChildren: () =&gt;<br>      import(&#39;./cart/cart.module&#39;).then((m) =&gt; m.CartModule), // Lazy-loaded Cart Page<br>  },<br>];</pre><h3>Basic Router</h3><p>The basic router is used to define and navigate between static routes.</p><p><strong>How to use:</strong></p><ol><li>Import RouterModule and Routes from @angular/router.</li><li>Define an array of routes, mapping paths to components.</li><li>Use &lt;router-outlet&gt; in the template to load the routed component.</li></ol><pre>// app-routing.module.ts<br>import { NgModule } from &#39;@angular/core&#39;;<br>import { RouterModule, Routes } from &#39;@angular/router&#39;;<br>import { HomeComponent } from &#39;./home/home.component&#39;;<br>import { AboutComponent } from &#39;./about/about.component&#39;;<br><br>const routes: Routes = [<br>  { path: &#39;&#39;, component: HomeComponent },<br>  { path: &#39;about&#39;, component: AboutComponent }<br>];<br><br>@NgModule({<br>  imports: [RouterModule.forRoot(routes)],<br>  exports: [RouterModule]<br>})<br>export class AppRoutingModule {}</pre><pre>&lt;!-- app.component.html --&gt;<br>&lt;nav&gt;<br>  &lt;a routerLink=&quot;/&quot;&gt;Home&lt;/a&gt;<br>  &lt;a routerLink=&quot;/about&quot;&gt;About&lt;/a&gt;<br>&lt;/nav&gt;<br>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><h3>Nested (Child) Routes</h3><p>Used when routes have a hierarchy, such as a parent route with child components.</p><p><strong>How to use:</strong></p><ol><li>Define child routes using the children property.</li><li>Include &lt;router-outlet&gt; in the parent component.</li></ol><p><strong>Example:</strong></p><pre>// app-routing.module.ts<br>const routes: Routes = [<br>  { <br>    path: &#39;dashboard&#39;, <br>    component: DashboardComponent,<br>    children: [<br>      { path: &#39;profile&#39;, component: ProfileComponent },<br>      { path: &#39;settings&#39;, component: SettingsComponent }<br>    ]<br>  }<br>];</pre><h3>Parameterized Routes</h3><p>Used to pass parameters in the route, often for fetching details based on an ID.</p><p><strong>How to use:</strong></p><ol><li>Define a route with a parameter (e.g., :id).</li><li>Use ActivatedRoute to access the parameter.</li></ol><pre>// app-routing.module.ts<br>const routes: Routes = [<br>  { path: &#39;product/:id&#39;, component: ProductComponent }<br>];</pre><pre>// product.component.ts<br>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { ActivatedRoute } from &#39;@angular/router&#39;;<br><br>@Component({<br>  selector: &#39;app-product&#39;,<br>  template: &#39;&lt;h1&gt;Product ID: {{ id }}&lt;/h1&gt;&#39;<br>})<br>export class ProductComponent implements OnInit {<br>  id!: string;<br><br>  constructor(private route: ActivatedRoute) {}<br><br>  ngOnInit() {<br>    this.id = this.route.snapshot.paramMap.get(&#39;id&#39;)!;<br>  }<br>}</pre><h3>Query Parameters</h3><p>Used to pass additional information via the URL without defining it in the route path.</p><p><strong>How to use:</strong></p><ol><li>Use Router to navigate with query parameters.</li><li>Retrieve query parameters with ActivatedRoute</li></ol><pre>// Navigation with query params<br>this.router.navigate([&#39;/products&#39;], { queryParams: { sort: &#39;price&#39;, order: &#39;asc&#39; } });</pre><pre>// app.component.ts<br>import { ActivatedRoute } from &#39;@angular/router&#39;;<br><br>ngOnInit() {<br>  this.route.queryParams.subscribe(params =&gt; {<br>    console.log(params); // { sort: &#39;price&#39;, order: &#39;asc&#39; }<br>  });<br>}</pre><h3>Redirect Routes</h3><p>Used to redirect from one route to another.</p><p><strong>How to use:</strong></p><ol><li>Define a route with the redirectTo property.</li></ol><pre>const routes: Routes = [<br>  { path: &#39;&#39;, redirectTo: &#39;/home&#39;, pathMatch: &#39;full&#39; },<br>  { path: &#39;home&#39;, component: HomeComponent }<br>];</pre><h3>Resolver Routes</h3><p>Used to fetch data before navigating to a route.</p><p><strong>How to use:</strong></p><ol><li>Create a resolver service implementing Resolve.</li><li>Use the resolve property in the route definition</li></ol><pre>// app-routing.module.ts<br>const routes: Routes = [<br>  { path: &#39;user/:id&#39;, component: UserComponent, resolve: { user: UserResolver } }<br>];</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbf28c81d7e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web API and Entity Framework Core for ASP.NET Core]]></title>
            <link>https://medium.com/@srishti.srajput/web-api-and-entity-framework-core-for-asp-net-core-e711623edbe5?source=rss-ccc6158bb7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e711623edbe5</guid>
            <category><![CDATA[aspnet]]></category>
            <dc:creator><![CDATA[Sriii]]></dc:creator>
            <pubDate>Thu, 30 May 2024 06:19:21 GMT</pubDate>
            <atom:updated>2024-05-30T06:25:02.290Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s start by understanding what an API is.</p><p>Let’s examine the application programming interface (API), which is a set of tools, protocols, and subroutine definitions used in the development of software and applications.</p><p>Different software and applications allow us to access APIs.</p><p>Our custom API can be saved and utilized by desktop, online, and mobile applications for Android, iPhone, and other platforms.</p><p>API stands for Application Programming Interface. It’s like a bridge that allows two different software applications to talk to each other.</p><h3>How Does an API Work?</h3><p>Imagine you are in a restaurant:</p><ol><li>You (the user) sit at a table with a menu of choices to order from.</li><li>The kitchen (the system) is where your order is prepared.</li><li>The waiter (the API) takes your order, tells the kitchen what to do, and brings the food back to you.</li></ol><p>In this scenario:</p><ul><li>The menu represents the API documentation that shows what you can ask for (available functions, data, etc.).</li><li>The waiter (API) takes your request (you want a burger) and tells the kitchen (system) what to do.</li><li>The kitchen prepares the food (the system processes your request) and the waiter delivers it back to you (the API sends the data back to you).</li></ul><h3>Why Use an API?</h3><p>APIs are used because they:</p><ol><li>Simplify communication: You don’t need to know how the kitchen works to get your food. Similarly, you don’t need to know the inner workings of a system to get data or functionality from it.</li><li>Allow integration: Different systems and applications can work together using APIs. For example, a weather app on your phone might use an API to get weather data from a remote server.</li><li>Improve efficiency: APIs allow developers to use existing code and functions rather than writing everything from scratch.</li></ol><h3>Real-World Example</h3><p>Let’s say you are using a travel app to book a flight. The travel app uses APIs to:</p><ul><li>Check available flights from various airlines.</li><li>Show prices and schedules.</li><li>Book your ticket.</li></ul><p>The app doesn’t store all this data itself. Instead, it makes requests to the airlines’ APIs, gets the information, and displays it for you.</p><h3>Key Points</h3><ul><li>Request: You ask the API for something (e.g., flight information).</li><li>Response: The API gives you back the data you asked for (e.g., list of available flights).</li><li>Endpoints: These are specific URLs where APIs can access the data (like different sections on a menu).</li></ul><h3>In Simple Terms</h3><p>An API is like a waiter in a restaurant who takes your order, delivers it to the kitchen, and brings back your food. You don’t need to know how the kitchen works to enjoy your meal. Similarly, with APIs, you don’t need to know how the system works to use its features or data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*oo3O5VK71ItezkzhsC2qbQ.png" /></figure><p>This is how Web api is usesful how they communicate with server (database) and client (application) using http protocols(get,post,put,delete) web api communcate with application using xml,json we get this type of file call them using angular then how they show based on ui/ux</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*pxNbm_JF4O75Xn0Rq9KiAg.png" /></figure><p>we create a web API one times uses in different application as we see in above diagram</p><h4>ASP.NET core Web API</h4><h4>ASP. Net core WEB Api is developed by Microsoft that allow you to build and create the restful Api using asp.net core platform.</h4><p>How asp.net web api follow the rule of restfule architecture and why lets see about restfule architecture</p><p>Learning first about all these lets see what is restful architecture</p><h3>What is REST Architecture</h3><h4>It is representational state transfer;<br>it introduces in 2000 by roy fielding.</h4><p>REST is a software architectural style that defines the set of rules to be used for creating web services.In rest architecture,a rest server simply and provide a access of the resourses and rest client provide access to and presents the resourses</p><p><strong>Architectural Constraints of RESTful API:</strong> There are six architectural constraints which makes any web service are listed below:</p><ul><li>Uniform Interface</li><li>Stateless</li><li>Cacheable</li><li>Client-Server</li><li>Layered System</li><li>Code on Demand</li></ul><ol><li>Uniform Interface:</li></ol><ul><li>This means that the way you interact with the API is consistent and standardized.</li><li>Resources (like data objects) are accessed using a common set of operations (such as GET, POST, PUT, DELETE).</li><li>This makes it easier to understand and use the API because you know how to interact with it without needing special instructions.</li></ul><p>2.Stateless:</p><ul><li>Each request from a client to the server must contain all the information needed to understand and process the request.</li><li>The server does not store any session information about the client between requests.</li><li>This makes the API scalable because each request can be handled independently.</li></ul><p>3.Cacheable:</p><ul><li>Responses from the server can be stored by the client or intermediate proxies to improve performance.</li><li>By caching responses, the client can avoid making repeated requests for the same data, reducing load on the server and speeding up the client’s experience.</li><li>The server must indicate which responses are cacheable and for how long.</li></ul><p>4.Client-Server:</p><ul><li>The API architecture separates the client (which requests data) from the server (which provides data).</li><li>This separation allows the client and server to evolve independently, as long as the interface between them doesn’t change.</li><li>It also improves scalability and flexibility because the client and server can be developed and maintained separately.</li></ul><p>5.Layered System:</p><ul><li>The architecture is organized into layers, with each layer having a specific responsibility.</li><li>For example, one layer might handle security, another might handle data storage, and another might handle business logic.</li><li>This structure helps to manage complexity and enhances flexibility, allowing layers to be modified or replaced without affecting the entire system.</li></ul><p>6.Code on Demand (optional):</p><p>The server can send executable code to the client to extend its functionality.</p><ul><li>For example, the server might send JavaScript code that the client can execute to process data locally.</li><li>This is optional and not always used, but it can add flexibility by allowing clients to download and run code as needed.</li></ul><p>In summary, these constraints ensure that a RESTful API is standardized, scalable, efficient, and flexible. By adhering to these principles, developers can create robust and maintainable web services.</p><h3>For document of web API and test of API we uses Swagger</h3><h3>Swagger</h3><h3>What is swagger</h3><p>it is used to describe the restful API <br>It also used to test the api.<br>swagger is also provide document in plain test or in human readable form that can be easy to understand</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjcwaRuneN_ZpdkcIq8Lmg.png" /></figure><p>these are the interface of swagger</p><p>lets see about the controller base class.</p><p>In controller folder there is one base class that is controllerBase this is base class it manage to http requests or protocols it provide the method or functinality to handle them http requests and generate the http responses <br>In controller directive there is attribute we call as [ApiController]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*8QXlanvo09OmBfLaRchr-g.png" /></figure><h3>Let’s look at the steps that we take to develop a web API in the AsP.net.</h3><p>step 1: Open the visual studio installer</p><p>step 2:click on create the new project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*gDWejpJbNrtN95UmlrTV8g.png" /></figure><p>step 3:click on ASP.net core web API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*i46Jdld0CEwgO4hVoa4dew.png" /></figure><p>step 4: Add these functinality while creating the project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*hdigibt8mrREkRVcYrcaBw.png" /></figure><p>step 5:Because the folder structure is similar to MVI but without a model, we created one. It now has a controller folder.</p><p>Step 6:when we click on create then this structure folder show</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*pcErdtIpzL33ZN4t9bWuYA.png" /></figure><p>this all how we create the web API project using asp.net core web api in version 6 .</p><h3>lets see how we create the controller</h3><p>We examine how to develop the controller for the Wep API in Asp.net v6</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*Ml-0VSh0Y4RgIXyTKEqMGw.png" /></figure><p>Here right click on controller folder then click on add dropdown click on controller then we have this interface</p><p>here click on API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*fiPFIQUaR62bLZzd1ADvoQ.png" /></figure><p>then here show the name of controller then click on create</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*XGTrAi0ith1J5juSRHQbnA.png" /></figure><p>click on add the controller and create controller.</p><p>Here is an example of how to create and utilize a controller. We are unable to connect to the database; instead, we can only view the list of users who have used this syntax.</p><pre> public List&lt;string&gt; Person = new List&lt;string&gt;()<br> {<br>     &quot;Srishti&quot;,<br>     &quot;Shraddha&quot;,<br>     &quot;Abishek&quot;,<br>     &quot;kajaldidu&quot;,<br>     &quot;anshika&quot;<br> };</pre><p>then get the list of person using get protocols</p><pre> [HttpGet]<br> public List&lt;string&gt; GetPerson()<br> {<br>     return Person;<br> }</pre><p>here get all the data.</p><pre>  [HttpGet(&quot;id&quot;)]<br>  public string GetId(int id)<br>  {<br>      return Person.ElementAt(id);<br>  }</pre><p>then the user enters to obtain the index, and from the index, the person data is obtained.</p><p>the specify data is found.</p><pre>using Microsoft.AspNetCore.Http;<br>using Microsoft.AspNetCore.Mvc;<br><br>namespace KRApplicationAPI.Controllers<br>{<br>    [Route(&quot;api/[controller]&quot;)]<br>    [ApiController]<br>    public class PersonController : ControllerBase<br>    {<br>        public List&lt;string&gt; Person = new List&lt;string&gt;()<br>        {<br>            &quot;Srishti&quot;,<br>            &quot;Shraddha&quot;,<br>            &quot;Abishek&quot;,<br>            &quot;kajaldidu&quot;,<br>            &quot;anshika&quot;<br>        };<br>        public PersonController() { <br>        <br>        }<br>        [HttpGet]<br>        public List&lt;string&gt; GetPerson()<br>        {<br>            return Person;<br>        }<br>        [HttpGet(&quot;id&quot;)]<br>        public string GetId(int id)<br>        {<br>            return Person.ElementAt(id);<br>        }<br>    }<br>}</pre><h3>ASP.NET Core Web API CRUD Operations Using Entity Framework Core And SQL Server</h3><p>these are steps 7:</p><p>We need these packages in order to connect to the backend SQL server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*e3Tdi2TzXdyPhq8lXsE83w.jpeg" /></figure><h3>note:</h3><p>When installing, all of these packages are chosen depending on the asp.net version of the project. For example, if the project is using version 6 of.net, install version 6’s entity framework core SQL and tools rather than version 7, as installing version 7 will result in an error.</p><p>also install microsoft entity framework design also</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*waZhhOt3X6Wu9f-u5L_KKg.png" /></figure><p>install all these .</p><p><strong>What are the change require while we create the project</strong></p><p><strong>asp.net core Web API</strong></p><p>Step 8:Create models of pre-existing tables from database(scaffolding)</p><p>Type in following command in the pm console and hit enter</p><p><strong>First create the DBCONtext means the context view of the data in models folders</strong></p><p><strong>Create the models folder than uses this command :</strong></p><p><strong>In TOOL-&gt;NuGet package manager-&gt; Package manager console.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0-Nd_x5hTqnQ5OuBtu0Zw.png" /></figure><p><em>Scaffold-DbContext “Server=IMSNASDTO00380\SQLEXPRESS;Database=KRdatabase;Trusted_Connection=True;Encrypt=False” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context KRdbcontext -Force</em></p><pre>Scaffold-DbContext &quot;Server=IMSNASDTO00380\SQLEXPRESS;Database=KRdatabase;Trusted_Connection=True;Encrypt=False&quot; Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context KRdbcontext -Force</pre><p><strong>“Server=”</strong> should be the name of your SQL server connection, you can check the exact name for this in SSMS when you are connecting to your db.</p><p><strong>“Database=”</strong> Should be the name for the specific database you want to connect to.</p><h3>Explanation of the Scaffold Command</h3><p>Connection String: “Server=IMSNASDTO00380\SQLEXPRESS;Database=KRdatabase;Trusted_Connection=True;Encrypt=False”</p><p>Provider: Microsoft.EntityFrameworkCore.SqlServer</p><p>Output Directory: -OutputDir Models (specifies the directory where the entity classes should be placed)</p><p>Context: -Context KRdbcontext (specifies the name of the DbContext class to generate)</p><p>Force: -Force (overwrites existing files)</p><p>When you have entered this command, visual studio works for a bit and after a few moments the context class will display, and in the solution explorer, a Models folder containing models of your database (and the dbcontext) will be created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*rYGXc6oE-YKM9xP0VwUPIQ.png" /></figure><p>Here if we update the DBContext also the databases uses migration if we want to add the tabel,attributes etc using asp.net uses all these.</p><p>If you delete the existing models and DbContext, you don&#39;t need to use migrations for the initial scaffolded code. Migrations are typically used in a code-first approach to apply changes to the database schema directly from your code. However, if you&#39;re using a database-first approach where the database schema is your source of truth, the use of migrations changes slightly.</p><p>Here’s a breakdown of the scenarios and their implications:</p><h3>1. Database-First Approach (Scaffolding)</h3><p>In this approach, you generate models and the DbContext from an existing database schema. This is often used when you already have a database and you want to create a .NET application that interacts with it.</p><h4>When to Use Scaffold:</h4><ul><li>Initial Model and Context Generation: When you first create the models and DbContext based on the existing database schema.</li><li>Updating Models: When the database schema changes and you want to update your models and DbContext to reflect those changes.</li></ul><h4>Steps:</h4><ol><li>Initial Scaffold: Generates the initial set of models and DbContext.</li></ol><pre>Scaffold-DbContext &quot;YourConnectionString&quot; Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context YourDbContextName -Force</pre><p>2.Re-Scaffold on Schema Changes: Whenever the database schema changes, you run the scaffold command again to update your models and DbContext.</p><h3>2. Code-First Approach (Migrations)</h3><p>In this approach, you define your models and DbContext in code first, and then use migrations to create and update the database schema.</p><h4>When to Use Migrations:</h4><ul><li>Initial Database Creation: When you want to create a new database from your code-first models.</li><li>Schema Updates: When you want to apply incremental changes to the database schema based on changes in your code-first models.</li></ul><h4>Steps:</h4><ol><li>Define Models and DbContext in Code:</li></ol><pre>public class ApplicationDbContext : DbContext<br>{<br>    public ApplicationDbContext(DbContextOptions&lt;ApplicationDbContext&gt; options) : base(options) { }<br><br>    public DbSet&lt;User&gt; Users { get; set; }<br>    // Add other DbSets for your entities<br>}<br><br>public class User<br>{<br>    public int Id { get; set; }<br>    public string Username { get; set; }<br>    public string Password { get; set; }<br>}</pre><p>2.Add Initial Migration:</p><pre>Add-Migration InitialCreate</pre><p>3.Update Database:</p><pre>Update-Database</pre><p>4.Apply Schema Changes:</p><ul><li>Make changes to your models.</li><li>Add a new migration:</li></ul><pre>Add-Migration UpdateUserSchema</pre><p>5.Update the database:</p><pre>Update-Database</pre><h3>Combining Database-First and Code-First Approaches</h3><p>In some projects, you might use a combination of both approaches. For example, you might start with a database-first approach to generate your initial models and DbContext, and then switch to code-first with migrations for subsequent schema changes.</p><h4>Steps for Combining Approaches:</h4><ol><li>Initial Scaffold: Generate models and DbContext from the existing database.</li></ol><pre>Scaffold-DbContext &quot;YourConnectionString&quot; Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context YourDbContextName -Force</pre><p>2.Apply Migrations for Subsequent Changes:</p><pre>Add-Migration YourMigrationName<br>Update-Database</pre><h3>Conclusion</h3><ul><li>Scaffolding: Use when you need to generate models and DbContext from an existing database. This is typically a one-time operation or done whenever the database schema changes.</li><li>Migrations: Use when you need to apply incremental changes to the database schema from your code. This is an ongoing process used to manage and apply schema changes over time.</li></ul><p>If you delete the generated models and DbContext and then re-scaffold them, you do not need migrations for this step. Migrations become useful when you are managing schema changes over time in a code-first approach or after the initial scaffold.</p><p>Step 9:create the controllers</p><blockquote>Create the constructors of controller using ctor command</blockquote><p>Then create the parameter of dB context of main class which contain all table.then click( ctrl dot(.)) and click on create and assign field of dropdown.</p><p>these are images i show</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cGK2WJh3SYCZHr-zHv5tbw.png" /></figure><p>While creating the DbConext in models delete all connection string and write them on appsetting.json.becauses it show some waring then write connection string in json file.</p><pre>&quot;ConnectionStrings&quot;: {<br>  &quot;DefaultConnection&quot;: &quot;Server=IMSNASDTO00380\\SQLEXPRESS;Database=KRdatabase;Trusted_Connection=True;Encrypt=False&quot;<br>},</pre><pre>{<br>  &quot;ConnectionStrings&quot;: {<br>    &quot;DefaultConnection&quot;: &quot;Server=IMSNASDTO00380\\SQLEXPRESS;Database=KRdatabase;Trusted_Connection=True;Encrypt=False&quot;<br>  },<br>  &quot;Logging&quot;: {<br>    &quot;LogLevel&quot;: {<br>      &quot;Default&quot;: &quot;Information&quot;,<br>      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;<br>    }<br>  },<br>  &quot;AllowedHosts&quot;: &quot;*&quot;<br>}</pre><p>then call the sql server ssms and controller etc in program.cs file</p><pre>builder.Services.AddControllers();<br>builder.Services.AddCors(options =&gt;<br>{<br>    options.AddPolicy(&quot;AllowAnyOrigin&quot;, builder =&gt;<br>    {<br>        builder.AllowAnyOrigin()<br>               .AllowAnyMethod()<br>               .AllowAnyHeader();<br>    });<br>});<br>// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle<br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();<br><br>builder.Services.AddDbContext&lt;KRdatabaseContext&gt;(options =&gt;<br>    options.UseSqlServer(builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));</pre><p>write all these command before</p><pre>var app = builder.Build();</pre><p>the whole code of starting file:Program.cs File</p><pre>using KRApplicationAPI.Models;<br>using Microsoft.EntityFrameworkCore;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>// Add services to the container.<br><br>builder.Services.AddControllers();<br>builder.Services.AddCors(options =&gt;<br>{<br>    options.AddPolicy(&quot;AllowAnyOrigin&quot;, builder =&gt;<br>    {<br>        builder.AllowAnyOrigin()<br>               .AllowAnyMethod()<br>               .AllowAnyHeader();<br>    });<br>});<br>// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle<br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();<br><br>builder.Services.AddDbContext&lt;KRdatabaseContext&gt;(options =&gt;<br>    options.UseSqlServer(builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));<br>var app = builder.Build();<br><br>// Configure the HTTP request pipeline.<br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI();<br>}<br><br>app.UseHttpsRedirection();<br>app.UseCors(&quot;AllowAnyOrigin&quot;);<br><br>app.UseAuthorization();<br><br>app.MapControllers();<br><br>app.Run();</pre><p>Now, we will add <a href="https://wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> (create, read, update, and delete) action methods to the controller.</p><p>Let’s start with the GET methods.</p><pre>[HttpGet]<br>public async Task&lt;ActionResult&lt;IEnumerable&lt;userdata&gt;&gt;&gt; GetData()<br>{<br>    return await _context.user.ToListAsync(); // Retrieve all user data<br>}</pre><h3>Explanation</h3><h4>[HttpGet]:</h4><p>This is an attribute that tells ASP.NET Core that this method should handle HTTP GET requests. When a client makes a GET request to the corresponding route, this method will be invoked.</p><p>2.public async Task&lt;ActionResult&lt;IEnumerable&lt;userdata&gt;&gt;&gt; GetData():</p><p>. public: This keyword means the method is accessible from outside the class. It&#39;s a public method.</p><ul><li>async: This keyword indicates that the method is asynchronous. Asynchronous methods can perform long-running tasks (like database queries) without blocking the main thread, which improves the application&#39;s responsiveness.</li><li>Task&lt;ActionResult&lt;IEnumerable&lt;userdata&gt;&gt;&gt;: This is the return type of the method.</li><li>Task: Indicates that the method performs an asynchronous operation and will eventually return a result.</li><li>ActionResult&lt;IEnumerable&lt;userdata&gt;&gt;: The actual result of the method. It is a generic type that:</li><li>ActionResult: Represents a result of an action method. It can return various HTTP responses, like 200 OK, 404 Not Found, etc.</li><li>IEnumerable&lt;userdata&gt;: A collection of userdata objects. This indicates that the method will return a collection of userdata items.</li></ul><p>3. { and }:</p><p>These curly braces define the start and end of the method body.</p><p>4.return await _context.user.ToListAsync();:</p><p>return: This keyword is used to return a result from the method.</p><ul><li>await: This keyword is used to asynchronously wait for the task to complete. It must be used in an async method.</li><li>_context.user: _context is an instance of DbContext, which represents the session with the database. user is the DbSet&lt;userdata&gt; representing the collection of userdata entities in the database.</li></ul><pre>public DbSet&lt;userdata&gt; user{ get; set; }</pre><ul><li>ToListAsync(): This is an asynchronous method that converts the IQueryable&lt;userdata&gt; to a List&lt;userdata&gt;. It executes the query against the database and retrieves all records in the user table.</li><li>The combination of await and ToListAsync() ensures that the database query runs asynchronously.</li></ul><h3>Summary</h3><ul><li>The [HttpGet] attribute specifies that this method handles HTTP GET requests.</li><li>The method GetData is asynchronous and returns a Task containing an ActionResult with an IEnumerable&lt;userdata&gt;.</li><li>Inside the method, await _context.user.ToListAsync() asynchronously queries the database to get all records from the user table and converts them to a list.</li><li>The return statement sends this list back to the client wrapped in an appropriate HTTP response.</li></ul><h3>Post methods:</h3><p>lets see</p><pre>[HttpPost]<br>public async Task&lt;ActionResult&lt;userdata&gt;&gt; AddData(userdata user)<br>{<br>    _context.user.Add(user); // Add the new user data to the context<br>    await _context.SaveChangesAsync(); // Save changes to the database<br>    return CreatedAtAction(nameof(GetDataById), new { id = user.Id }, user); // Return the newly created user<br>}</pre><h3>Explanation of Each Line</h3><ol><li>Method Attribute: [HttpPost]</li></ol><pre>[HttpPost]</pre><ul><li>This attribute indicates that this method will handle HTTP POST requests. POST requests are typically used to create new resources on the server.</li></ul><p>2.Method Declaration: public async Task&lt;ActionResult&lt;userdata&gt;&gt; AddData(userdata user)</p><pre>public async Task&lt;ActionResult&lt;userdata&gt;&gt; AddData(userdata user)</pre><ul><li>public: The method is accessible from other parts of the application.</li><li>async: The method is asynchronous, meaning it can perform tasks without blocking the execution thread.</li><li>Task&lt;ActionResult&lt;userdata&gt;&gt;: The method returns a task that results in an ActionResult of type userdata. This is suitable for asynchronous methods in ASP.NET Core that return HTTP responses.</li><li>AddData: The name of the method.</li><li>userdata user: The method takes a parameter user of type userdata. This parameter is expected to be provided in the body of the POST request.</li></ul><p>3.Add User to Context: _context.user.Add(user);</p><pre>_context.user.Add(user); // Add the new user data to the context</pre><ul><li>_context: This is an instance of the database context class, which allows you to interact with the database.</li><li>user: The entity set in the context where userdata objects are stored.</li><li>Add(user): This method adds the new userdata object to the context, marking it as to be inserted into the database when SaveChangesAsync is called.</li></ul><p>Save Changes to Database:</p><pre>await _context.SaveChangesAsync();</pre><ul><li>await: This keyword indicates that the method should asynchronously wait for the operation to complete.</li><li>_context.SaveChangesAsync(): This method saves all changes made in the context to the database. By calling this, the new userdata object is actually inserted into the database.</li></ul><p>5.Return Created Response: return CreatedAtAction(nameof(GetDataById), new { id = user.Id }, user);</p><pre>return CreatedAtAction(nameof(GetDataById), new { id = user.Id }, user); // Return the newly created user</pre><ul><li>CreatedAtAction: This method returns an HTTP 201 Created response. It’s used to indicate that a new resource has been successfully created.</li><li>nameof(GetDataById): This specifies the name of the action method that can be used to retrieve the created resource. GetDataById is another method in the controller that returns a single userdata by its ID.</li><li>new { id = user.Id }: This is an anonymous object that provides the route values. Here, it’s specifying the ID of the newly created user, so the URL for fetching this user can be generated.</li><li>user: The newly created userdata object that is included in the response body.</li></ul><h3>Summary</h3><ul><li>The method handles HTTP POST requests to create new user data.</li><li>It adds the new user to the database context.</li><li>It saves the changes to the database asynchronously.</li><li>It returns an HTTP 201 Created response, including the location where the new user can be retrieved and the new user data.</li></ul><p>This method ensures that new user data is correctly added to the database and provides a standardized HTTP response indicating the successful creation of the resource.</p><h3>[HttpGet(“{id}”)]</h3><p>Explanation: This attribute specifies that this action method responds to HTTP GET requests and takes an id parameter from the URL.</p><ul><li>Usage: If you send a GET request to https://yourapi.com/api/controllerName/123, the 123 part will be passed as the id parameter to the method.</li></ul><pre>[HttpGet(&quot;{id}&quot;)]<br>public async Task&lt;ActionResult&lt;userdata&gt;&gt; GetDataById(string id)<br>{<br>    var user = await _context.user.FindAsync(id); // Find the user by ID<br><br>    if (user == null)<br>    {<br>        return NotFound(); // Return 404 if user is not found<br>    }<br><br>    return user; // Return the found user<br>}</pre><h3>Explanation</h3><ol><li>[HttpGet(“{id}”)]</li></ol><p>Explanation: This attribute specifies that this action method responds to HTTP GET requests and takes an id parameter from the URL.</p><ul><li>Usage: If you send a GET request to https://yourapi.com/api/controllerName/123, the 123 part will be passed as the id parameter to the method.</li></ul><p>public async Task&lt;ActionResult&lt;userdata&gt;&gt; GetDataById(string id)</p><p>Explanation: This is the method signature.</p><ul><li>public: The method is accessible from outside the class.</li><li>async: Indicates that the method is asynchronous, meaning it can perform operations without blocking the main thread.</li><li>Task&lt;ActionResult&lt;userdata&gt;&gt;: The method returns a Task that will eventually provide an ActionResult&lt;userdata&gt;. This allows for async operations.</li><li>GetDataById: The name of the method.</li><li>string id: The method takes a single parameter, id, which is a string. This will be the ID of the user we want to find.</li></ul><ol><li>var user = await _context.user.FindAsync(id);</li></ol><ul><li>Explanation: This line attempts to find a user in the database with the given id.</li><li>var user: Declares a variable named user to store the result of the database query.</li><li>await: Waits for the database query to complete asynchronously.</li><li>_context.user.FindAsync(id): Uses the Entity Framework Core FindAsync method to search for a user with the specified id in the user table (_context.user represents the users table in the database).</li></ul><p>if (user == null)</p><p>Explanation: Checks if the user variable is null.</p><p>This means that no user with the given id was found in the database.</p><p>{ return NotFound(); }</p><p>Explanation: If the user was not found (user == null), the method returns a NotFound result.</p><p>NotFound(): A built-in method that returns a 404 HTTP status code, indicating that the requested resource was not found.</p><p>return user;</p><p>Explanation: If the user was found (user != null), the method returns the user.</p><p>This implicitly wraps the user in an ActionResult&lt;userdata&gt;, meaning the framework will handle converting it to an appropriate HTTP response.</p><h3>Summary</h3><ul><li>The method listens for GET requests at the endpoint api/controllerName/{id}.</li><li>It retrieves a user from the database using the provided id.</li><li>If no user is found, it returns a 404 Not Found response.</li><li>If a user is found, it returns the user.</li></ul><p>This method effectively handles the retrieval of a specific user by their ID, providing clear feedback if the user does not exist in the database.</p><h3>[HttpPut(“{id}”)]</h3><pre> [HttpPut(&quot;{id}&quot;)]<br> public async Task&lt;IActionResult&gt; UpdateUserPassword(string id, userdata updatedUser)<br> {<br>     if (id != updatedUser.Id)<br>     {<br>         return BadRequest(&quot;User ID mismatch.&quot;); // Return 400 if the IDs do not match<br>     }<br><br>     _context.Entry(updatedUser).State = EntityState.Modified; // Mark the entity as modified<br><br>     try<br>     {<br>         await _context.SaveChangesAsync(); // Save changes to the database<br>     }<br>     catch (DbUpdateConcurrencyException)<br>     {<br>         if (!UserExists(id))<br>         {<br>             return NotFound(); // Return 404 if the user does not exist<br>         }<br>         else<br>         {<br>             throw; // Re-throw the exception if it&#39;s another issue<br>         }<br>     }<br><br>     return NoContent(); // Return 204 No Content on successful update<br> }<br><br> private bool UserExists(string id)<br> {<br>     return _context.user.Any(e =&gt; e.Id == id); // Check if a user with the given ID exists<br> }</pre><h3>Method Signature</h3><pre>[HttpPut(&quot;{id}&quot;)]<br>public async Task&lt;IActionResult&gt; UpdateUserPassword(string id, userdata updatedUser)</pre><ul><li>[HttpPut(“{id}”)]: This tells the API that this method should handle HTTP PUT requests, and the {id} part means it will take an ID from the URL.</li><li>public async Task&lt;IActionResult&gt; UpdateUserPassword(string id, userdata updatedUser): This defines an asynchronous method that returns an IActionResult. It takes two parameters: id from the URL and updatedUser which is the updated user data.</li></ul><h3>ID Mismatch Check:</h3><pre>if (id != updatedUser.Id)<br>{<br>    return BadRequest(&quot;User ID mismatch.&quot;);<br>}</pre><ul><li>if (id != updatedUser.Id): This checks if the ID from the URL does not match the ID in the updated user data.</li><li>return BadRequest(“User ID mismatch.”);: If the IDs don’t match, it returns a 400 Bad Request response with the message “User ID mismatch.”</li></ul><h3>Mark Entity as Modified</h3><pre>_context.Entry(updatedUser).State = EntityState.Modified;</pre><ul><li>_context.Entry(updatedUser).State = EntityState.Modified;: This tells the database context that the updatedUser object has been modified and needs to be updated in the database.</li></ul><h3>Save Changes in a Try-Catch Block</h3><pre>try<br>{<br>    await _context.SaveChangesAsync();<br>}<br>catch (DbUpdateConcurrencyException)<br>{<br>    if (!UserExists(id))<br>    {<br>        return NotFound();<br>    }<br>    else<br>    {<br>        throw;<br>    }<br>}</pre><ul><li>try { await _context.SaveChangesAsync(); }: This tries to save the changes to the database. The await keyword is used because it&#39;s an asynchronous operation.</li><li>catch (DbUpdateConcurrencyException): If there’s a problem saving the changes due to concurrency issues (e.g., the data was updated by someone else), this block will handle the error.</li><li>if (!UserExists(id)) { return NotFound(); }: This checks if the user with the given ID exists in the database. If not, it returns a 404 Not Found response.</li><li>else { throw; }: If the user exists but there’s another issue, it re-throws the exception to be handled elsewhere.</li></ul><h3>Return No Content on Success</h3><pre>return NoContent();</pre><ul><li>return NoContent();: If everything goes well, this returns a 204 No Content response, indicating that the update was successful but there is no content to return.</li></ul><h3>Helper Method to Check User Existence</h3><pre>private bool UserExists(string id)<br>{<br>    return _context.user.Any(e =&gt; e.Id == id);<br>}</pre><ul><li>private bool UserExists(string id): This is a private method that checks if a user with the given ID exists in the database.</li><li>return _context.user.Any(e =&gt; e.Id == id);: It queries the database to see if any user has the specified ID and returns true if a user is found, false otherwise.</li></ul><h3>Summary</h3><ul><li>Check for ID Mismatch: First, ensure the ID from the URL matches the ID in the user data.</li><li>Mark the Data as Modified: Tell the context that the user data has been changed.</li><li>Try to Save Changes: Attempt to save the changes, handling any concurrency issues that might occur.</li><li>Return No Content on Success: If successful, respond with 204 No Content.</li><li>Helper Method: A method to check if a user exists in the database by their ID.</li></ul><p>This method updates a user’s password in the database, ensuring that the user ID in the URL matches the user ID in the data being updated. If there’s an error, it handles it appropriately, ensuring the database remains consistent.</p><p>The whole code of controller to perform the crud operation</p><pre>using KRApplicationAPI.Models;<br>using Microsoft.AspNetCore.Http;<br>using Microsoft.AspNetCore.Mvc;<br>using Microsoft.EntityFrameworkCore;<br>using System.Collections.Generic;<br>using System.Threading.Tasks;<br><br>namespace KRApplicationAPI.Controllers<br>{<br>    [Route(&quot;api/[controller]&quot;)]<br>    [ApiController]<br>    public class LogindataController : ControllerBase<br>    {<br>        private readonly KRdatabaseContext _context;<br><br>        public LogindataController(KRdatabaseContext context)<br>        {<br>            _context = context;<br>        }<br><br><br>        // POST: api/Logindata<br>        [HttpPost]<br>        public async Task&lt;ActionResult&lt;userdata&gt;&gt; AddData(userdata user)<br>        {<br>            _context.user.Add(user); // Add the new user data to the context<br>            await _context.SaveChangesAsync(); // Save changes to the database<br>            return CreatedAtAction(nameof(GetDataById), new { id = user.Id }, user); // Return the newly created user<br>        }<br><br>        // GET: api/Logindata<br>        [HttpGet]<br>        public async Task&lt;ActionResult&lt;IEnumerable&lt;userdata&gt;&gt;&gt; GetData()<br>        {<br>            return await _context.user.ToListAsync(); // Retrieve all user data<br>        }<br><br>        // GET: api/Logindata/{id}<br>        [HttpGet(&quot;{id}&quot;)]<br>        public async Task&lt;ActionResult&lt;userdata&gt;&gt; GetDataById(string id)<br>        {<br>            var user = await _context.user.FindAsync(id); // Find the user by ID<br><br>            if (user == null)<br>            {<br>                return NotFound(); // Return 404 if user is not found<br>            }<br><br>            return user; // Return the found user<br>        }<br><br>        // PUT: api/Logindata/{id}<br>        [HttpPut(&quot;{id}&quot;)]<br>        public async Task&lt;IActionResult&gt; UpdateUserPassword(string id, userdata updatedUser)<br>        {<br>            if (id != updatedUser.Id)<br>            {<br>                return BadRequest(&quot;User ID mismatch.&quot;); // Return 400 if the IDs do not match<br>            }<br><br>            _context.Entry(updatedUser).State = EntityState.Modified; // Mark the entity as modified<br><br>            try<br>            {<br>                await _context.SaveChangesAsync(); // Save changes to the database<br>            }<br>            catch (DbUpdateConcurrencyException)<br>            {<br>                if (!UserExists(id))<br>                {<br>                    return NotFound(); // Return 404 if the user does not exist<br>                }<br>                else<br>                {<br>                    throw; // Re-throw the exception if it&#39;s another issue<br>                }<br>            }<br><br>            return NoContent(); // Return 204 No Content on successful update<br>        }<br><br>        private bool UserExists(string id)<br>        {<br>            return _context.user.Any(e =&gt; e.Id == id); // Check if a user with the given ID exists<br>        }<br>    }<br>}</pre><p>This is the complete code needed to carry out the crub action.</p><p>REFERANCES:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSszvaPH7IxM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSszvaPH7IxM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSszvaPH7IxM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/61b555f6ab83e96175004dd160664ecc/href">https://medium.com/media/61b555f6ab83e96175004dd160664ecc/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FyLHWt-1aSCQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DyLHWt-1aSCQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FyLHWt-1aSCQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6371041b0bf22640b37a0c3e1465708a/href">https://medium.com/media/6371041b0bf22640b37a0c3e1465708a/href</a></iframe><p><strong>Consultation: This article explains everything about how to construct an API using Asp.Net, including what an API is, what a controller is, and how to utilize it.</strong></p><h3>SORT WAY to define all of these</h3><h3>Summary of ASP.NET Core Web API Development</h3><p>ASP.NET Core Web API is a framework used to build web APIs for different types of applications, like web, mobile, and desktop apps.</p><h4>Steps to Develop and Maintain an ASP.NET Core Web API</h4><ol><li>Set Up the Project:</li></ol><p>Create a New Project: Start a new ASP.NET Core Web API project.Install Packages: Ensure you have Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.SqlServer installed.</p><p>2.Generate DbContext and Models:Scaffold the DbContext and Models: Use the scaffold command to create DbContext and models from an existing database.</p><pre>Scaffold-DbContext &quot;YourConnectionString&quot; Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context YourDbContextName -Force</pre><ul><li>This command reads your database schema and creates classes in the Models folder.</li></ul><p>3.Make Changes to the Database:</p><p>Update the Database: Directly update your database schema using a tool like SQL Server Management Studio.</p><p>4.Update DbContext and Models:</p><p>Re-scaffold: Run the scaffold command again to update your DbContext and models to match the new database schema.</p><pre>Scaffold-DbContext &quot;YourConnectionString&quot; Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context YourDbContextName -Force</pre><p>5.Use Migrations for Code-First Changes:</p><p>Initial Migration: Create an initial migration if starting with code-first.</p><pre>Add-Migration InitialCreate<br>Update-Database</pre><p>Subsequent Migrations: When you change your models in code, use migrations to update the database.</p><pre>Add-Migration YourMigrationName<br>Update-Database</pre><p>6.Generate Controllers:</p><ul><li>Scaffold Controllers: Use scaffolding to generate controllers that handle CRUD operations for your models.</li></ul><pre>Scaffold-Controller -Model YourModelName -DataContext YourDbContextName -OutputDir Controllers</pre><h3>Summary</h3><ul><li>ASP.NET Core Web API: A framework to build APIs.</li><li>Scaffolding: Generate DbContext and models from your database.</li><li>Database Changes: Directly update your database schema.</li><li>Re-scaffold: Update models and DbContext to match database changes.</li><li>Migrations: Use to apply changes from your code to the database.</li><li>Controllers: Scaffold to handle CRUD operations.</li></ul><p>This process helps you keep your code and database in sync, making it easier to develop and maintain your ASP.NET Core Web API.</p><h4>Thank u all for being part of this ASP.net core web api</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e711623edbe5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bootstrap background color and css color ,opacity,how we get good combine color]]></title>
            <link>https://medium.com/@srishti.srajput/bootstrap-background-color-and-css-color-opacity-how-we-get-good-combine-color-0a5feb21d4fd?source=rss-ccc6158bb7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a5feb21d4fd</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[colors]]></category>
            <category><![CDATA[bootstrap-template]]></category>
            <category><![CDATA[bootstrap]]></category>
            <dc:creator><![CDATA[Sriii]]></dc:creator>
            <pubDate>Tue, 07 May 2024 13:01:06 GMT</pubDate>
            <atom:updated>2024-05-07T13:01:06.704Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bootstrap background color and css color ,opacity,how we get good combine color</h3><h3>Background Colors</h3><p>The classes for background colors are: .bg-primary, .bg-success, .bg-info, .bg-warning, .bg-danger, .bg-secondary, .bg-dark and .bg-light.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*uQhGXK_zAOORrNkdlzFR-g.png" /></figure><p>The .bg-<em>color</em> classes above does not work well with text, or atleast then you have to specify a proper .text-<em>color</em> class to get the right text color for each background.</p><p>However, you can use the .text-bg-<em>color</em> classes and Bootstrap will automatically handle the appropriate text color for each background color:</p><h3>Example</h3><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;title&gt;Bootstrap Example&lt;/title&gt;<br>  &lt;meta charset=&quot;utf-8&quot;&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>  &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot;&gt;<br>  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js&quot;&gt;&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br><br>&lt;div class=&quot;container mt-3&quot;&gt;<br>  &lt;h2&gt;Background Color with Contrasting Text Color&lt;/h2&gt;<br>  &lt;p class=&quot;text-bg-primary&quot;&gt;This text is important.&lt;/p&gt;<br>  &lt;p class=&quot;text-bg-success&quot;&gt;This text indicates success.&lt;/p&gt;<br>  &lt;p class=&quot;text-bg-info&quot;&gt;This text represents some information.&lt;/p&gt;<br>  &lt;p class=&quot;text-bg-warning&quot;&gt;This text represents a warning.&lt;/p&gt;<br>  &lt;p class=&quot;text-bg-danger&quot;&gt;This text represents danger.&lt;/p&gt;<br>  &lt;p class=&quot;text-bg-secondary&quot;&gt;Secondary background color.&lt;/p&gt;<br>  &lt;p class=&quot;text-bg-dark&quot;&gt;Dark grey background color.&lt;/p&gt;<br>  &lt;p class=&quot;text-bg-light&quot;&gt;Light grey background color.&lt;/p&gt;<br>&lt;/div&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*yyJK5lOt0ktAC-wlkqlhtQ.png" /><figcaption>text-bg-*(uses)</figcaption></figure><h3>Text Colors</h3><p>Bootstrap 5 has some contextual classes that can be used to provide “meaning through colors”.</p><p>The classes for text colors are: .text-muted, .text-primary, .text-success, .text-info, .text-warning, .text-danger, .text-secondary, .text-white, .text-dark, .text-body (default body color/often black) and .text-light:</p><h3>Background gradient</h3><p>By adding a .bg-gradient class, a linear gradient is added as background image to the backgrounds. This gradient starts with a semi-transparent white which fades out to the bottom.</p><p>Do you need a gradient in your custom CSS? Just add background-image: var(--bs-gradient);.</p><pre>  &lt;p class=&quot;bg-primary bg-gradient&quot;&gt;Light grey background color.&lt;/p&gt;</pre><figure><img alt="this gradiant color we want to uses we can uses it" src="https://cdn-images-1.medium.com/max/843/1*-_nKfK5MHRMDeYuCHfrHNw.png" /><figcaption>Gradient colors</figcaption></figure><h3>Utility variables</h3><p>Not every utility class uses CSS variables, but the ones that do gain a good amount of power and customization. <a href="https://getbootstrap.com/docs/5.2/utilities/background/">Background</a>, <a href="https://getbootstrap.com/docs/5.2/utilities/borders/">border</a>, and <a href="https://getbootstrap.com/docs/5.2/utilities/colors/">color</a> utilities all have what we call “local CSS variables” to improve their usefulness. Each of them uses CSS variables to customize the alpha transparency value of rgba() colors.</p><p>Consider our <a href="https://getbootstrap.com/docs/5.2/utilities/background/">background color utilities</a>, .bg-*. By default each utility class has a local variable, --bs-bg-opacity with a default value of 1. To change the background utility alpha value, you can override that value with your own styles, or some new .bg-opacity-* utilities.</p><pre>&lt;div class=&quot;p-3 bg-success bg-opacity-25&quot;&gt;<br>  ...<br>&lt;/div&gt;</pre><pre>&lt;div class=&quot;p-3 bg-warning bg-opacity-75&quot;&gt;<br>&lt;/div&gt;</pre><p>Here’s how .bg-success looks with all our .bg-opacity-* classes applied:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*Qg2V0oGy83wY4zuDZOxaOw.png" /></figure><p>opacity in background .</p><p>And the same is available for <a href="https://getbootstrap.com/docs/5.2/utilities/borders/#opacity">border color opacity</a> (--bs-border-opacity and .border-opacity-*) and <a href="https://getbootstrap.com/docs/5.2/utilities/colors/#opacity">text color opacity</a> (--bs-text-opacity and .text-opacity-*). So many color options are now available with these utilities.</p><p>By default, we ship with five values for these various opacity utilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*VDoA_kVdLqhl_j-rlg2cpQ.png" /><figcaption>opacity of text,background,border</figcaption></figure><p>How can we choose the colors that work best for our website? Which website offers you the most color combinations, let’s look?</p><p>here are the first website two search for combine colors</p><ul><li><a href="https://mycolor.space/">ColorSpace - Color Palettes Generator and Color Gradient Tool</a></li><li><a href="https://flatuicolors.com/">Flat UI Colors 2 - 14 Color Palettes, 280 colors 🎨</a></li><li><a href="https://colorhunt.co/">Color Hunt - Color Palettes for Designers and Artists</a></li></ul><p><a href="https://www.pinterest.com/alrdr97/colour-combination/">https://www.pinterest.com/alrdr97/colour-combination</a>/</p><p><a href="https://www.colorcombos.com/">Color Combinations | Color Schemes | Color Palettes</a></p><p>Note:To choose a color, first observe the psyclophy of colors:and websites with simple color palettes, such as YouTube, Google, and others, work well because they display differently against light or dark backgrounds.</p><p>Step 1:Search for color psyclophy read the meaning of color</p><p>Step 2:Then follow the the 60–30–10 rule in interior design rule</p><p>Step 3: See the cultural meaning of color using website</p><ul><li><a href="https://www.empower-yourself-with-color-psychology.com/cultural-color.html">Cultural Color</a></li><li><a href="https://atlassian.design/foundations/color-new">Color</a></li></ul><p>here are some color check them with the rule</p><p><a href="https://color.adobe.com/">https://color.adobe.com/</a></p><p>and also some semantic color</p><p>here are some sementic color how we give a warning using yellow ,orange color how we give a alte using red info using green</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*uPsDFeQlEYvbl9uwqxJaJQ.png" /><figcaption>Warning color</figcaption></figure><p>Here are the code how we add background color using css and bootstrap</p><p>lets see using coding</p><pre>&lt;div class=&quot;p-3 mb-2 bg-primary text-white&quot;&gt;.bg-primary&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-primary-subtle text-primary-emphasis&quot;&gt;.bg-primary-subtle&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-secondary text-white&quot;&gt;.bg-secondary&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-secondary-subtle text-secondary-emphasis&quot;&gt;.bg-secondary-subtle&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-success text-white&quot;&gt;.bg-success&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-success-subtle text-success-emphasis&quot;&gt;.bg-success-subtle&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-danger text-white&quot;&gt;.bg-danger&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-danger-subtle text-danger-emphasis&quot;&gt;.bg-danger-subtle&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-warning text-dark&quot;&gt;.bg-warning&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-warning-subtle text-warning-emphasis&quot;&gt;.bg-warning-subtle&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-info text-dark&quot;&gt;.bg-info&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-info-subtle text-info-emphasis&quot;&gt;.bg-info-subtle&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-light text-dark&quot;&gt;.bg-light&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-light-subtle text-light-emphasis&quot;&gt;.bg-light-subtle&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-dark text-white&quot;&gt;.bg-dark&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-dark-subtle text-dark-emphasis&quot;&gt;.bg-dark-subtle&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-body-secondary&quot;&gt;.bg-body-secondary&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-body-tertiary&quot;&gt;.bg-body-tertiary&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-body text-body&quot;&gt;.bg-body&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-black text-white&quot;&gt;.bg-black&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-white text-dark&quot;&gt;.bg-white&lt;/div&gt;<br>&lt;div class=&quot;p-3 mb-2 bg-transparent text-body&quot;&gt;.bg-transparent&lt;/div&gt;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*PW5t8ncm68ec7PbEQZgT0Q.png" /></figure><p><a href="https://getbootstrap.com/docs/5.3/customize/color/#colors">Color · Bootstrap v5.3 (getbootstrap.com)</a></p><p>this are quite good document for colors in bootstrap how we set for ui/ux design.</p><p>lets see how we add text color using bootstrap and css also here are the code</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>    &lt;title&gt;text colors&lt;/title&gt;<br>    &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; integrity=&quot;sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH&quot; crossorigin=&quot;anonymous&quot;&gt;<br>    &lt;style&gt;<br>        #back{<br>            background-color: rgb(173, 106, 236);<br>        }<br>        #text{<br>            color:brown;<br>        }<br>    &lt;/style&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;h2&gt;colors checker using bootstrap text color class&lt;/h2&gt;<br>    &lt;span class=&quot;text-black&quot;&gt;Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptate temporibus, voluptatibus neque atque dolor maiores tempore cupiditate maxime placeat modi quam deleniti ducimus doloribus explicabo possimus laboriosam rerum quod odit?&lt;/span&gt;<br>    &lt;span class=&quot;text-bg-info&quot;&gt;Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptate temporibus, voluptatibus neque atque dolor maiores tempore cupiditate maxime placeat modi quam deleniti ducimus doloribus explicabo possimus laboriosam rerum quod odit?&lt;/span&gt;<br>    &lt;span class=&quot;text-primary&quot;&gt;Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptate temporibus, voluptatibus neque atque dolor maiores tempore cupiditate maxime placeat modi quam deleniti ducimus doloribus explicabo possimus laboriosam rerum quod odit?&lt;/span&gt;<br><br>    &lt;h1&gt;how we add color using css lets see&lt;/h1&gt;<br>    &lt;span id=&quot;back&quot;&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit. Distinctio assumenda itaque quidem nesciunt. Delectus ratione sunt facilis nemo sapiente ab eligendi doloribus temporibus odit consequatur neque amet, distinctio, tempore cumque?&lt;/span&gt;<br>    &lt;span id=&quot;text&quot;&gt;Lorem ipsum dolor sit amet consectetur adipisicing elit. Molestiae eum, cupiditate voluptatibus nam necessitatibus, odit, qui porro est voluptates eos quas reiciendis nihil assumenda quis nesciunt illum eius eveniet officiis.&lt;/span&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js&quot; integrity=&quot;sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>The output is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKGfAIR51-eHsAo6lECUfg.png" /></figure><p>here how we create the colore link</p><p><a href="https://getbootstrap.com/docs/5.3/helpers/colored-links/">Colored links · Bootstrap v5.3 (getbootstrap.com)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a5feb21d4fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Responsive sidebar creation using bootstrap.]]></title>
            <link>https://medium.com/@srishti.srajput/responsive-sidebar-creation-using-bootstrap-0d198fd1d931?source=rss-ccc6158bb7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d198fd1d931</guid>
            <category><![CDATA[responsive]]></category>
            <dc:creator><![CDATA[Sriii]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 13:17:14 GMT</pubDate>
            <atom:updated>2024-04-16T13:17:14.326Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Responsive sidebar creation using bootstrap.</strong></p><p>To make the HTML code easier to understand, we break it up into chunks.</p><blockquote>Step 1:Write the basic HTML code first, then add the bootstrap and lineicon cdn.the lineicon is used for adding good icon to our sidebar or any navbar</blockquote><pre>html<br>&lt;html&gt;<br>&lt;head&gt;<br>&lt;title&gt;Sample creation of sidebar&lt;/title&gt;<br>&lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Sidebar With Bootstrap&lt;/title&gt;<br>    &lt;link href=&quot;https://cdn.lineicons.com/4.0/lineicons.css&quot; rel=&quot;stylesheet&quot; /&gt;<br>    &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot;<br>        integrity=&quot;sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ&quot; crossorigin=&quot;anonymous&quot;&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt;<br>&lt;/head&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br> &lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js&quot;<br>        integrity=&quot;sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe&quot;<br>        crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<br><br></pre><blockquote>Step 2:Using the id #sidebar, enter the aside tag inside the wrapper class that you created with tag div.after that, make the d-flex class with a div tag inside of it, add a grid button, and make another class as a sidelogo with a div tag inside of it by calling Kcode to generate the logo.</blockquote><pre>  &lt;div class=&quot;wrapper&quot;&gt;<br>        &lt;aside id=&quot;sidebar&quot;&gt;<br>            &lt;div class=&quot;d-flex&quot;&gt;<br>                &lt;button class=&quot;toggle-btn&quot; type=&quot;button&quot;&gt;<br>                    &lt;i class=&quot;lni lni-grid-alt&quot;&gt;&lt;/i&gt;<br>                &lt;/button&gt;<br>                &lt;div class=&quot;sidebar-logo&quot;&gt;<br>                    &lt;a href=&quot;#&quot;&gt;CodzSword&lt;/a&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;</pre><blockquote>Step 3:After that create the list of items in ul for navbar .here see</blockquote><pre>  &lt;ul class=&quot;sidebar-nav&quot;&gt;<br>                &lt;li class=&quot;sidebar-item&quot;&gt;<br>                    &lt;a href=&quot;#&quot; class=&quot;sidebar-link&quot;&gt;<br>                        &lt;i class=&quot;lni lni-user&quot;&gt;&lt;/i&gt;<br>                        &lt;span&gt;Profile&lt;/span&gt;<br>                    &lt;/a&gt;<br>                &lt;/li&gt;</pre><blockquote>then how we create the dropdown lets see?search for this for follow the link</blockquote><blockquote><a href="https://getbootstrap.com/docs/5.3/components/accordion/#how-it-works">Accordion · Bootstrap v5.3 (getbootstrap.com)</a></blockquote><blockquote>Initially, look up bootstrap, then type an<strong> accordion</strong>. If we search for anything in <strong>Lionicon,</strong> it will also provide you with a <strong>decent icon.</strong></blockquote><blockquote>for bootstrap we take these data</blockquote><pre>data-bs-toggle=&quot;collapse&quot; data-bs-target=&quot;#collapseOne&quot; aria-expanded=&quot;true&quot; aria-controls=&quot;collapseOne&quot;<br>for a&lt;abbreication&gt; href tags<br> for ul<br><br>data-bs-parent=&quot;#accordionExample&quot;&gt;<br>write the parent name here<br></pre><blockquote>here see how i write</blockquote><blockquote>here i write aria-expanded as false change data-bs-target and aria-controls and put the same #id also we change this <br>data-bs-parent=”#sidebar”</blockquote><pre> &lt;li class=&quot;sidebar-item&quot;&gt;<br>                    &lt;a href=&quot;#&quot; class=&quot;sidebar-link collapsed has-dropdown&quot; data-bs-toggle=&quot;collapse&quot;<br>                        data-bs-target=&quot;#auth&quot; aria-expanded=&quot;false&quot; aria-controls=&quot;auth&quot;&gt;<br>                        &lt;i class=&quot;lni lni-protection&quot;&gt;&lt;/i&gt;<br>                        &lt;span&gt;Auth&lt;/span&gt;<br>                    &lt;/a&gt;<br>                    &lt;ul id=&quot;auth&quot; class=&quot;sidebar-dropdown list-unstyled collapse&quot; data-bs-parent=&quot;#sidebar&quot;&gt;<br>                        &lt;li class=&quot;sidebar-item&quot;&gt;<br>                            &lt;a href=&quot;#&quot; class=&quot;sidebar-link&quot;&gt;Login&lt;/a&gt;<br>                        &lt;/li&gt;<br>                        &lt;li class=&quot;sidebar-item&quot;&gt;<br>                            &lt;a href=&quot;#&quot; class=&quot;sidebar-link&quot;&gt;Register&lt;/a&gt;<br>                        &lt;/li&gt;<br>                    &lt;/ul&gt;<br>                &lt;/li&gt;<br>                &lt;li class=&quot;sidebar-item&quot;&gt;<br>                    &lt;a href=&quot;#&quot; class=&quot;sidebar-link collapsed has-dropdown&quot; data-bs-toggle=&quot;collapse&quot;<br>                        data-bs-target=&quot;#multi&quot; aria-expanded=&quot;false&quot; aria-controls=&quot;multi&quot;&gt;<br>                        &lt;i class=&quot;lni lni-layout&quot;&gt;&lt;/i&gt;<br>                        &lt;span&gt;Multi Level&lt;/span&gt;<br>                    &lt;/a&gt;<br>                    &lt;ul id=&quot;multi&quot; class=&quot;sidebar-dropdown list-unstyled collapse&quot; data-bs-parent=&quot;#sidebar&quot;&gt;<br>                        &lt;li class=&quot;sidebar-item&quot;&gt;<br>                            &lt;a href=&quot;#&quot; class=&quot;sidebar-link collapsed&quot; data-bs-toggle=&quot;collapse&quot;<br>                                data-bs-target=&quot;#multi-two&quot; aria-expanded=&quot;false&quot; aria-controls=&quot;multi-two&quot;&gt;<br>                                Two Links<br>                            &lt;/a&gt;<br>                            &lt;ul id=&quot;multi-two&quot; class=&quot;sidebar-dropdown list-unstyled collapse&quot;&gt;<br>                                &lt;li class=&quot;sidebar-item&quot;&gt;<br>                                    &lt;a href=&quot;#&quot; class=&quot;sidebar-link&quot;&gt;Link 1&lt;/a&gt;<br>                                &lt;/li&gt;<br>                                &lt;li class=&quot;sidebar-item&quot;&gt;<br>                                    &lt;a href=&quot;#&quot; class=&quot;sidebar-link&quot;&gt;Link 2&lt;/a&gt;<br>                                &lt;/li&gt;<br>                            &lt;/ul&gt;<br>                        &lt;/li&gt;<br>                    &lt;/ul&gt;<br>                &lt;/li&gt;</pre><blockquote>lets see in brief</blockquote><blockquote>This code is a part of a sidebar navigation menu commonly used in web applications. Let’s break it down:<br>&lt;li class=”sidebar-item”&gt;</blockquote><blockquote>This &lt;li&gt; element represents a single item in the sidebar navigation menu. It has the class sidebar-item.</blockquote><blockquote>&lt;a href=”#” class=”sidebar-link collapsed has-dropdown” data-bs-toggle=”collapse”<br> data-bs-target=”#auth” aria-expanded=”false” aria-controls=”auth”&gt;<br> &lt;i class=”lni lni-protection”&gt;&lt;/i&gt;<br> &lt;span&gt;Auth&lt;/span&gt;<br>&lt;/a&gt;</blockquote><blockquote>Inside the &lt;li&gt;, there&#39;s an &lt;a&gt; element representing a link. It has the class sidebar-link. The href=&quot;#&quot; means that the link doesn&#39;t navigate anywhere specific (# usually means it stays on the same page). The class collapsed indicates that the dropdown menu is initially collapsed. has-dropdown indicates that this link has a dropdown menu associated with it. The data-bs-toggle and data-bs-target attributes are used by Bootstrap&#39;s JavaScript to toggle the collapse behavior. aria-expanded=&quot;false&quot; and aria-controls=&quot;auth&quot; are accessibility attributes indicating the current state of the dropdown menu.</blockquote><blockquote>Inside the &lt;a&gt;, there&#39;s an &lt;i&gt; element representing an icon, and a &lt;span&gt; element containing the text &quot;Auth&quot;.</blockquote><blockquote>&lt;ul id=”auth” class=”sidebar-dropdown list-unstyled collapse” data-bs-parent=”#sidebar”&gt;</blockquote><blockquote>This &lt;ul&gt; element represents the dropdown menu associated with the &quot;Auth&quot; link. It has the class sidebar-dropdown. The id=&quot;auth&quot; is used as the target for the dropdown toggle. The class list-unstyled removes the default list styling, and collapse initially collapses the dropdown menu. data-bs-parent=&quot;#sidebar&quot; specifies that the parent of this dropdown menu is an element with the ID sidebar.</blockquote><blockquote>Inside this &lt;ul&gt;, there are two &lt;li&gt; elements representing the items in the dropdown menu: &quot;Login&quot; and &quot;Register&quot;. Each &lt;li&gt; has the class sidebar-item, and inside it, there&#39;s an &lt;a&gt; element with the class sidebar-link representing the actual links.</blockquote><blockquote>Overall, this code creates a sidebar navigation item labeled “Auth” with a dropdown menu containing “Login” and “Register” options. The dropdown menu is collapsed by default and can be toggled to expand or collapse by clicking on the “Auth” link.</blockquote><blockquote>here whole html code?</blockquote><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br><br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Sidebar With Bootstrap&lt;/title&gt;<br>    &lt;link href=&quot;https://cdn.lineicons.com/4.0/lineicons.css&quot; rel=&quot;stylesheet&quot; /&gt;<br>    &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot;<br>        integrity=&quot;sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ&quot; crossorigin=&quot;anonymous&quot;&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>    &lt;div class=&quot;wrapper&quot;&gt;<br>        &lt;aside id=&quot;sidebar&quot;&gt;<br>            &lt;div class=&quot;d-flex&quot;&gt;<br>                &lt;button class=&quot;toggle-btn&quot; type=&quot;button&quot;&gt;<br>                    &lt;i class=&quot;lni lni-grid-alt&quot;&gt;&lt;/i&gt;<br>                &lt;/button&gt;<br>                &lt;div class=&quot;sidebar-logo&quot;&gt;<br>                    &lt;a href=&quot;#&quot;&gt;KCode&lt;/a&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;ul class=&quot;sidebar-nav&quot;&gt;<br>                &lt;li class=&quot;sidebar-item&quot;&gt;<br>                    &lt;a href=&quot;#&quot; class=&quot;sidebar-link&quot;&gt;<br>                        &lt;i class=&quot;lni lni-user&quot;&gt;&lt;/i&gt;<br>                        &lt;span&gt;Profile&lt;/span&gt;<br>                    &lt;/a&gt;<br>                &lt;/li&gt;<br>                &lt;li class=&quot;sidebar-item&quot;&gt;<br>                    &lt;a href=&quot;#&quot; class=&quot;sidebar-link&quot;&gt;<br>                        &lt;i class=&quot;lni lni-agenda&quot;&gt;&lt;/i&gt;<br>                        &lt;span&gt;Task&lt;/span&gt;<br>                    &lt;/a&gt;<br>                &lt;/li&gt;<br>                &lt;li class=&quot;sidebar-item&quot;&gt;<br>                    &lt;a href=&quot;#&quot; class=&quot;sidebar-link collapsed has-dropdown&quot; data-bs-toggle=&quot;collapse&quot;<br>                        data-bs-target=&quot;#auth&quot; aria-expanded=&quot;false&quot; aria-controls=&quot;auth&quot;&gt;<br>                        &lt;i class=&quot;lni lni-protection&quot;&gt;&lt;/i&gt;<br>                        &lt;span&gt;Auth&lt;/span&gt;<br>                    &lt;/a&gt;<br>                    &lt;ul id=&quot;auth&quot; class=&quot;sidebar-dropdown list-unstyled collapse&quot; data-bs-parent=&quot;#sidebar&quot;&gt;<br>                        &lt;li class=&quot;sidebar-item&quot;&gt;<br>                            &lt;a href=&quot;#&quot; class=&quot;sidebar-link&quot;&gt;Login&lt;/a&gt;<br>                        &lt;/li&gt;<br>                        &lt;li class=&quot;sidebar-item&quot;&gt;<br>                            &lt;a href=&quot;#&quot; class=&quot;sidebar-link&quot;&gt;Register&lt;/a&gt;<br>                        &lt;/li&gt;<br>                    &lt;/ul&gt;<br>                &lt;/li&gt;<br>                &lt;li class=&quot;sidebar-item&quot;&gt;<br>                    &lt;a href=&quot;#&quot; class=&quot;sidebar-link collapsed has-dropdown&quot; data-bs-toggle=&quot;collapse&quot;<br>                        data-bs-target=&quot;#multi&quot; aria-expanded=&quot;false&quot; aria-controls=&quot;multi&quot;&gt;<br>                        &lt;i class=&quot;lni lni-layout&quot;&gt;&lt;/i&gt;<br>                        &lt;span&gt;Multi Level&lt;/span&gt;<br>                    &lt;/a&gt;<br>                    &lt;ul id=&quot;multi&quot; class=&quot;sidebar-dropdown list-unstyled collapse&quot; data-bs-parent=&quot;#sidebar&quot;&gt;<br>                        &lt;li class=&quot;sidebar-item&quot;&gt;<br>                            &lt;a href=&quot;#&quot; class=&quot;sidebar-link collapsed&quot; data-bs-toggle=&quot;collapse&quot;<br>                                data-bs-target=&quot;#multi-two&quot; aria-expanded=&quot;false&quot; aria-controls=&quot;multi-two&quot;&gt;<br>                                Two Links<br>                            &lt;/a&gt;<br>                            &lt;ul id=&quot;multi-two&quot; class=&quot;sidebar-dropdown list-unstyled collapse&quot;&gt;<br>                                &lt;li class=&quot;sidebar-item&quot;&gt;<br>                                    &lt;a href=&quot;#&quot; class=&quot;sidebar-link&quot;&gt;Link 1&lt;/a&gt;<br>                                &lt;/li&gt;<br>                                &lt;li class=&quot;sidebar-item&quot;&gt;<br>                                    &lt;a href=&quot;#&quot; class=&quot;sidebar-link&quot;&gt;Link 2&lt;/a&gt;<br>                                &lt;/li&gt;<br>                            &lt;/ul&gt;<br>                        &lt;/li&gt;<br>                    &lt;/ul&gt;<br>                &lt;/li&gt;<br>                &lt;li class=&quot;sidebar-item&quot;&gt;<br>                    &lt;a href=&quot;#&quot; class=&quot;sidebar-link&quot;&gt;<br>                        &lt;i class=&quot;lni lni-popup&quot;&gt;&lt;/i&gt;<br>                        &lt;span&gt;Notification&lt;/span&gt;<br>                    &lt;/a&gt;<br>                &lt;/li&gt;<br>                &lt;li class=&quot;sidebar-item&quot;&gt;<br>                    &lt;a href=&quot;#&quot; class=&quot;sidebar-link&quot;&gt;<br>                        &lt;i class=&quot;lni lni-cog&quot;&gt;&lt;/i&gt;<br>                        &lt;span&gt;Setting&lt;/span&gt;<br>                    &lt;/a&gt;<br>                &lt;/li&gt;<br>            &lt;/ul&gt;<br>            &lt;div class=&quot;sidebar-footer&quot;&gt;<br>                &lt;a href=&quot;#&quot; class=&quot;sidebar-link&quot;&gt;<br>                    &lt;i class=&quot;lni lni-exit&quot;&gt;&lt;/i&gt;<br>                    &lt;span&gt;Logout&lt;/span&gt;<br>                &lt;/a&gt;<br>            &lt;/div&gt;<br>        &lt;/aside&gt;<br>        &lt;div class=&quot;main p-3&quot;&gt;<br>            &lt;div class=&quot;text-center&quot;&gt;<br>                &lt;h1&gt;<br>                    Sidebar Bootstrap 5<br>                &lt;/h1&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js&quot;<br>        integrity=&quot;sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe&quot;<br>        crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br><br>&lt;/html&gt;<br></pre><blockquote>Step 4:Let’s write about how I added the CSS and how that changed the content.</blockquote><pre>@import url(https://medium.com/&#39;https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&amp;display=swap&#39;);<br>::after,<br>::before {<br>    box-sizing: border-box;<br>    margin: 0;<br>    padding: 0;<br>}<br><br>a {<br>    text-decoration: none;<br>}<br><br>li {<br>    list-style: none;<br>}<br><br>h1 {<br>    font-weight: 600;<br>    font-size: 1.5rem;<br>}<br><br>body {<br>    font-family: &#39;Poppins&#39;, sans-serif;<br>}</pre><blockquote>@import: This is a CSS rule used to bring in external resources like fonts or stylesheets into your CSS file.</blockquote><blockquote>URL: It specifies the location of the external resource you want to import.</blockquote><blockquote>Google Fonts API: This is where the font “Poppins” is hosted.</blockquote><blockquote>family=Poppins: It tells the browser to import the “Poppins” font.</blockquote><blockquote>:wght@400;600: This specifies which weights of the font to import. Here, it’s importing the regular (400) and semi-bold (600) weights.</blockquote><blockquote>&amp;display=swap: This tells the browser to use a technique called “font-display: swap”, which ensures that text remains visible while the font is loading, improving performance.</blockquote><blockquote>So, in simple terms, this line of code is bringing in the “Poppins” font from Google Fonts in two weights (regular and semi-bold) and making sure the text remains visible even while the font is loading for better user experience.</blockquote><blockquote>first we show the whole css code</blockquote><pre>@import url(https://medium.com/&#39;https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&amp;display=swap&#39;);<br><br>::after,<br>::before {<br>    box-sizing: border-box;<br>    margin: 0;<br>    padding: 0;<br>}<br><br>a {<br>    text-decoration: none;<br>}<br><br>li {<br>    list-style: none;<br>}<br><br>h1 {<br>    font-weight: 600;<br>    font-size: 1.5rem;<br>}<br><br>body {<br>    font-family: &#39;Poppins&#39;, sans-serif;<br>}<br><br>.wrapper {<br>    display: flex;<br>}<br><br>.main {<br>    min-height: 100vh;<br>    width: 100%;<br>    overflow: hidden;<br>    transition: all 0.35s ease-in-out;<br>    background-color: #fafbfe;<br>}<br><br>#sidebar {<br>    width: 70px;<br>    min-width: 70px;<br>    z-index: 1000;<br>    transition: all .25s ease-in-out;<br>    background-color: #0e2238;<br>    display: flex;<br>    flex-direction: column;<br>}<br><br>#sidebar.expand {<br>    width: 260px;<br>    min-width: 260px;<br>}<br><br>.toggle-btn {<br>    background-color: transparent;<br>    cursor: pointer;<br>    border: 0;<br>    padding: 1rem 1.5rem;<br>}<br><br>.toggle-btn i {<br>    font-size: 1.5rem;<br>    color: #FFF;<br>}<br><br>.sidebar-logo {<br>    margin: auto 0;<br>}<br><br>.sidebar-logo a {<br>    color: #FFF;<br>    font-size: 1.15rem;<br>    font-weight: 600;<br>}<br><br>#sidebar:not(.expand) .sidebar-logo,<br>#sidebar:not(.expand) a.sidebar-link span {<br>    display: none;<br>}<br><br>.sidebar-nav {<br>    padding: 2rem 0;<br>    flex: 1 1 auto;<br>}<br><br>a.sidebar-link {<br>    padding: .625rem 1.625rem;<br>    color: #FFF;<br>    display: block;<br>    font-size: 0.9rem;<br>    white-space: nowrap;<br>    border-left: 3px solid transparent;<br>}<br><br>.sidebar-link i {<br>    font-size: 1.1rem;<br>    margin-right: .75rem;<br>}<br><br>a.sidebar-link:hover {<br>    background-color: rgba(255, 255, 255, .075);<br>    border-left: 3px solid #3b7ddd;<br>}<br><br>.sidebar-item {<br>    position: relative;<br>}<br><br>#sidebar:not(.expand) .sidebar-item .sidebar-dropdown {<br>    position: absolute;<br>    top: 0;<br>    left: 70px;<br>    background-color: #0e2238;<br>    padding: 0;<br>    min-width: 15rem;<br>    display: none;<br>}<br><br>#sidebar:not(.expand) .sidebar-item:hover .has-dropdown+.sidebar-dropdown {<br>    display: block;<br>    max-height: 15em;<br>    width: 100%;<br>    opacity: 1;<br>}<br><br>#sidebar.expand .sidebar-link[data-bs-toggle=&quot;collapse&quot;]::after {<br>    border: solid;<br>    border-width: 0 .075rem .075rem 0;<br>    content: &quot;&quot;;<br>    display: inline-block;<br>    padding: 2px;<br>    position: absolute;<br>    right: 1.5rem;<br>    top: 1.4rem;<br>    transform: rotate(-135deg);<br>    transition: all .2s ease-out;<br>}<br><br>#sidebar.expand .sidebar-link[data-bs-toggle=&quot;collapse&quot;].collapsed::after {<br>    transform: rotate(45deg);<br>    transition: all .2s ease-out;<br>}<br></pre><pre>const hamBurger = document.querySelector(&quot;.toggle-btn&quot;);<br><br>hamBurger.addEventListener(&quot;click&quot;, function () {<br>  document.querySelector(&quot;#sidebar&quot;).classList.toggle(&quot;expand&quot;);<br>});</pre><blockquote>This JavaScript code adds interactivity to the sidebar toggle button:</blockquote><pre>const hamBurger = document.querySelector(&quot;.toggle-btn&quot;);</pre><blockquote>This line selects the HTML element with the class toggle-btn and assigns it to the variable hamBurger.</blockquote><pre>hamBurger.addEventListener(&quot;click&quot;, function () {<br>  document.querySelector(&quot;#sidebar&quot;).classList.toggle(&quot;expand&quot;);<br>});</pre><blockquote>This code adds a click event listener to the hamBurger element. When the button is clicked, the function inside the event listener is executed.</blockquote><blockquote>Inside the function:</blockquote><blockquote>document.querySelector(&quot;#sidebar&quot;) selects the sidebar element with the ID sidebar.</blockquote><blockquote>.classList.toggle(&quot;expand&quot;) toggles the presence of the class expand on the selected element. If the element has the class, it removes it; if it doesn&#39;t have the class, it adds it.</blockquote><blockquote>So, when the toggle button is clicked, it toggles the expand class on the sidebar, which controls whether the sidebar expands or collapses. If the sidebar is expanded, clicking the button collapses it, and vice versa.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d198fd1d931" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>