<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Omama Aslam</title>
    <description>The latest articles on DEV Community by Omama Aslam (@omamaaslam).</description>
    <link>https://dev.to/omamaaslam</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1148829%2F1a5da74c-5ce1-4419-b06d-2f075a0ff43b.png</url>
      <title>DEV Community: Omama Aslam</title>
      <link>https://dev.to/omamaaslam</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/omamaaslam"/>
    <language>en</language>
    <item>
      <title>What is the difference between slice() and splice() javascript array methods and how to use them</title>
      <dc:creator>Omama Aslam</dc:creator>
      <pubDate>Sun, 21 Jan 2024 08:23:21 +0000</pubDate>
      <link>https://dev.to/omamaaslam/what-is-the-difference-between-slice-and-splice-javascript-array-methods-and-how-to-use-them-1170</link>
      <guid>https://dev.to/omamaaslam/what-is-the-difference-between-slice-and-splice-javascript-array-methods-and-how-to-use-them-1170</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvungf21gt3unxwr74url.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvungf21gt3unxwr74url.png" alt="Image description" width="800" height="865"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this article, I will walk you through how to use the slice() and splice() array methods using code examples.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to use the slice() JavaScript array method
&lt;/h2&gt;

&lt;p&gt;The slice() method can be used to create a copy of an array or return a portion of an array. It is important to note that the slice() method does not alter the original array but instead creates a shallow copy.&lt;br&gt;
Here is the basic syntax:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;slice(optional start parameter, optional end parameter)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Let's take a look at some examples to better understand how the slice() method works.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to use the slice() JavaScript method without the start and end parameters
&lt;/h2&gt;

&lt;p&gt;In this first example, I have created a list of cities from around the world.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;const cities =["Lahore","Islamabad","Karachi","Multan","Peshwar", "Quetta"];&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;I can use the slice() method to create a shallow copy of that array.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;cities.slice()&lt;/code&gt;&lt;br&gt;
When I console.log the result, then I will see all of the elements from my cities array copied into this new array. Just like :- ["Lahore","Islamabad","Karachi","Multan","Peshwar", "Quetta"]&lt;/p&gt;

&lt;h2&gt;
  
  
  How to use the slice() JavaScript method using the start parameter
&lt;/h2&gt;

&lt;p&gt;You can use the optional start parameter to set a starting position for selecting elements from the array. It is important to remember that arrays are zero based indexed. In this example, we will set the start position at index 2 which will select the last three cities in the array and return them in a new array.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;const newCityArr = cities.slice(2);&lt;br&gt;
 console.log(newCityArr)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Here is the result :- ["Karachi","Multan","Peshwar", "Quetta"]&lt;br&gt;
The original array was not modified as we can see here in the above example.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to use the splice() JavaScript array method
&lt;/h2&gt;

&lt;p&gt;Unlike the slice() method, the splice() method will change the contents of the original array. The splice() method is used to add or remove elements of an existing array and the return value will be the removed items from the array.&lt;br&gt;
If nothing was removed from the array, then the return value will just be an empty array. Here is the basic syntax.&lt;br&gt;
&lt;code&gt;splice(start, optional delete count, optional items to add)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In this example, we have an array of food items.&lt;br&gt;
&lt;code&gt;const food = ['pizza', 'cake', 'salad', 'cookie'];&lt;/code&gt;&lt;br&gt;
If we wanted to add another food item to the array at index 1, then we can use the following code:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;food.splice(1,0,"burrito")&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The first number is the starting index, and the second number is the delete count. Since we are not deleting any items, our delete count is zero.&lt;/p&gt;

&lt;p&gt;This is what the result would look like in the console.&lt;/p&gt;

&lt;p&gt;`const food = ['pizza', 'cake', 'salad', 'cookie'];&lt;/p&gt;

&lt;p&gt;food.splice(1,0,"burrito")&lt;/p&gt;

&lt;p&gt;console.log(food)`&lt;/p&gt;

&lt;p&gt;and result will be: ['pizza', 'burrito', 'cake', 'salad', 'cookie']&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;The slice and splice array methods might seem similar to each other, but there are a few key differences.&lt;/p&gt;

&lt;p&gt;The slice() method can be used to create a copy of an array or return a portion of an array. It is important to note that the slice() method does not alter the original array but instead creates a shallow copy. &lt;/p&gt;

&lt;p&gt;Unlike the slice() method, the splice() method will change the contents of the original array. The splice() method is used to add or remove elements of an existing array and the return value will be the removed items from the array.&lt;/p&gt;

&lt;p&gt;If nothing was removed from the array, then the return value will just be an empty array.&lt;/p&gt;

&lt;p&gt;I hope you enjoyed this JavaScript article and best of luck on your developer journey. Also don't forget to share will your friends and do also comment if you find this blog helpful.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1uw0hn4bgtv3uywxucp4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1uw0hn4bgtv3uywxucp4.png" alt="Image description" width="800" height="865"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>arrayinjavascript</category>
      <category>arraymodification</category>
      <category>beginnerprogramming</category>
      <category>javascriptarraymethods</category>
    </item>
    <item>
      <title>Object-Oriented Programming Concepts in Angular (OOP Paradigm)</title>
      <dc:creator>Omama Aslam</dc:creator>
      <pubDate>Mon, 01 Jan 2024 06:05:15 +0000</pubDate>
      <link>https://dev.to/omamaaslam/object-oriented-programming-concepts-in-angular-oop-paradigm-m9n</link>
      <guid>https://dev.to/omamaaslam/object-oriented-programming-concepts-in-angular-oop-paradigm-m9n</guid>
      <description>&lt;p&gt;Introduction:&lt;/p&gt;

&lt;p&gt;Object-oriented programming (OOP) is a programming paradigm that is widely used in Angular, a popular web development framework. OOP helps to make code more modular, reusable, and easier to maintain. However, implementing OOP principles in Angular can be challenging, especially for developers who are new to the framework. In this blog, we will explore the key OOP concepts in Angular and how they can be used to build better web applications. We will also highlight Omama’s expertise in Angular and how it can help you build scalable and maintainable web applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Object-Oriented Programming (OOP) Concepts in Angular:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Encapsulation: Encapsulation is a core principle of OOP, and it is essential for building scalable and maintainable web applications. In Angular, encapsulation refers to the process of binding data and methods to a component, module, or service, and preventing them from being accessed from outside the module. Encapsulation helps to prevent data corruption and ensures that code is modular and reusable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Abstraction: Abstraction is another key OOP principle that is important in Angular. Abstraction refers to the process of hiding the implementation details of a module, component, or service and exposing only the necessary information to the user. Abstraction helps to simplify complex systems and makes them easier to use.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Inheritance: Inheritance is a powerful OOP concept that is used in Angular to create hierarchies of components, services, and modules. Inheritance allows developers to reuse code and build more complex systems by inheriting properties and methods from a parent class. In Angular, inheritance is used to build components, services, and modules that share common functionality.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Polymorphism: Polymorphism is another essential OOP concept that is used in Angular to create dynamic, flexible systems. Polymorphism refers to the ability of an object to take on multiple forms, depending on the context. In Angular, polymorphism is used to create components, services, and modules that can be used in different contexts and with different data types.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Encapsulation in Angular:&lt;/strong&gt; In Angular, encapsulation is achieved through the use of access modifiers, such as public, private, and protected. By default, all properties and methods of a component, module, or service in Angular are public, which means they can be accessed from outside the module. However, by using the private or protected access modifier, developers can limit the accessibility of properties and methods to within the module only. This helps to prevent data corruption and ensures that the code is modular and reusable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Abstraction in Angular:&lt;/strong&gt; Abstraction in Angular is achieved through the use of interfaces and abstract classes. An interface is a contract that specifies the properties and methods that a class must implement. By using an interface, developers can ensure that the class implements the required functionality and can be used interchangeably with other classes that implement the same interface. An abstract class, on the other hand, is a class that cannot be instantiated and can only be used as a base class for other classes. Abstract classes can contain abstract methods, which are methods that do not have an implementation and must be implemented by the derived class.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Inheritance in Angular:&lt;/strong&gt; Inheritance in Angular is achieved through the use of the extends keyword. By using the extends keyword, developers can create a hierarchy of components, services, and modules, where a child class inherits properties and methods from its parent class. Inheritance helps to reduce code duplication and allows developers to reuse code and build more complex systems.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Polymorphism in Angular:&lt;/strong&gt; Polymorphism in Angular is achieved through the use of interfaces and abstract classes. By using interfaces, developers can create components, services, and modules that can be used in different contexts and with different data types. For example, a component that implements an interface can be used interchangeably with other components that implement the same interface. Similarly, abstract classes can be used as a base class for other classes, allowing developers to create components, services, and modules that share common functionality.&lt;/p&gt;

</description>
      <category>objectorientedprogramming</category>
      <category>abstraction</category>
      <category>oopconcept</category>
      <category>angularprogramming</category>
    </item>
    <item>
      <title>What is Interceptor in Angular and how to use Interceptor in Angular</title>
      <dc:creator>Omama Aslam</dc:creator>
      <pubDate>Mon, 06 Nov 2023 07:04:52 +0000</pubDate>
      <link>https://dev.to/omamaaslam/what-is-interceptor-in-angular-and-how-to-use-interceptor-in-angular-32mm</link>
      <guid>https://dev.to/omamaaslam/what-is-interceptor-in-angular-and-how-to-use-interceptor-in-angular-32mm</guid>
      <description>&lt;p&gt;*&lt;em&gt;In this artical we are going to learn : *&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;What is an Angular HTTP Interceptor&lt;/li&gt;
&lt;li&gt;How to Create HTTP Interceptor&lt;/li&gt;
&lt;li&gt;10 Ways to Use Interceptors in Angular&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;An application is incomplete without the backend server that displays data on UI. Various backend servers are available on the internet. Most application uses JSON and XML servers to perform their tasks. The API is used for the backend communication between components and methods. This communication is based on two significant concepts: authorization and authentication. &lt;/p&gt;

&lt;p&gt;Interceptors are another significant part of Angular programming. They are used to modify the HTTP requests by adding several functionalities.&lt;/p&gt;

&lt;p&gt;Authentication determines the security level of an application. The authentication check is placed on the user’s identity to make a good connection.&lt;/p&gt;

&lt;p&gt;In contrast to this, authorization is a concept used to determine a user's authority.&lt;/p&gt;

&lt;p&gt;Interceptor in angular is a great way to modify your code and make it more readable. Also, they are used in various other fields, which we will discuss later.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is an Angular HTTP Interceptor
&lt;/h2&gt;

&lt;p&gt;The angular interceptor is a medium connecting the backend and front-end applications. Whenever a request is made, the interceptors handle it in between. They can also identify the response by performing Rxjs operators. The interceptor is used to perform various functions and methods to perform specific tasks.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Create HTTP Interceptor
&lt;/h2&gt;

&lt;p&gt;Before implementing an angular interceptor, you must create one. So, here we will help you create a service that will implement the HTTP interceptor angular interface. Here are the code snippets and examples to create an interceptor of your own.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;First, create an injectable service.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Injectable() export class AppHttpInterceptor implements HttpInterceptor {
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Now, implement the intercept method within the above class.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;intercept(req: HttpRequest&amp;lt;any&amp;gt;, next: HttpHandler): Observable&amp;lt;HttpEvent&amp;lt;any&amp;gt;&amp;gt; {
// do whatever you want to do with this request
return next.handle(req);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Then add the class within the root module. Use the token named HTTP_INTERCEPTOR.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AppHttpInterceptor,
multi: true
}
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  10 Ways to Use Interceptors in Angular
&lt;/h2&gt;

&lt;p&gt;There are various ways to use the angular HTTP interceptor. We have selected the top 10 most straightforward ways to use the angular HTTP interceptor. We will study them with relevant codes and examples. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Loaders &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Interceptors can be used as loaders whenever there exist different active requests. A loader function with both, hide and show features is used to handle the requests. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;URL &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Changing the URLs is what the interceptor angular is capable of. You can change the URL, and the interceptor will behave like an API interceptor used to add prefixes.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Headers &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Angular interceptors manipulate the headers as they provide features such as authentication and authorization. The angular HTTP interceptors are used to protect the application against XSRF.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Converting &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Interceptor can even convert the format of an API that we receive. A more likely example is to convert the XML file to a JSON file.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Errors &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Interceptors are used in two ways to detect the errors- retry the HTTP call, and the second one is to keep a check on the status of the exception that occurred.&lt;/p&gt;

&lt;p&gt;There are various HTTP error codes such as error codes 400, 500, and 200 and their series, which are to be handled individually. The error code 500 determines that the API has not received the request. The error code 401 means that the access token is no longer active.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Notifications &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Interceptors can even show various messages as notifications. In the below example, we have printed an “object created” message on the console. The notifications can also be displayed whenever we detect an error.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return next.handle(req).pipe(
tap((event: HttpEvent&amp;lt;any&amp;gt;) =&amp;gt;{ 
 if(event instanceof HttpResponse &amp;amp;&amp;amp; event.status === 200) {
  this.toastr.success("Object Created");
}
})
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Fake backend &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;As the name suggests, the fake backend is used to develop the application when the backend doesn’t exist. The response is based on the request, after which we return an observable object of the HTTP request. The code snippet is attached below-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const body = { 
 FirstName: "Omama",
 LastName: "Aslam"
};

return of(new HttpResponse({ status: 200, body: body}));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Profiling &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Interceptors have the ability to both requests and respond simultaneously. They can even log the HTTP operation without any time delay. So, it becomes easy to note the time of both the request and the response and can be consoled together.&lt;/p&gt;

&lt;p&gt;Different profiles can be logged into the database to get the information.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const started = Date.now();
let ok: string;

return next.handle(req).pipe(
tap(
(event: HttpEvent&amp;lt;any&amp;gt;) = ok = event instanceof HttpResponse ? 'successed' : '', 
(error: HttpErrorResponse) =&amp;gt; ok: 'failed'
), 
finalize(()=&amp;gt;{
const elapsed = date.now() - started;
const msg = `${req.method} "${req.urlWithParams}" ${ok} in ${elapsed} ms.`
})
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Authentication &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Authentication is the basic functionality added to any application to check the user’s authentication. This is a common and basic use of the interceptors to make a check-in at the application’s usage. It connects various parameters such as the refresh tokens, adds bearer tokens, and redirects to the login URL. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Catching &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Interceptors are capable enough to detect any errors as it handles the requests besides forwarding them to the handle method. We will use a key-value map where the key will be more like a URL. The observable response can be returned directly to the handle function as soon as we find any relevant response on the map.&lt;/p&gt;

&lt;p&gt;This is feasible as it saves a lot of time and energy. The developers do not always need to search everything in the backend when they have already caught one.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AuthService } from '../weblib/services/auth.service';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    constructor(private authService: AuthService,
        private router: Router) { }

    intercept(request: HttpRequest&amp;lt;any&amp;gt;, next: HttpHandler): Observable&amp;lt;HttpEvent&amp;lt;any&amp;gt;&amp;gt; {
        return next.handle(request).pipe(catchError(err =&amp;gt; {
            if ((err.status === 401 || err.status === 403) &amp;amp;&amp;amp; !request.url.includes('unauth')) {
                // auto logout if 401 response returned from api
                this.authService.logout(true);
                //this.router.navigate(['login']);
                location.reload(true);
            }
            // tslint:disable-next-line:max-line-length
            let error = 'Unable to process request at this time. If problem persists please notify your admin.';
            //if (err.error) { error = err.error.message || err.error.error; }
            if (err.error) { error = err.error.exceptionMessage || err.error || err.message; }
            return throwError(`Status: ${err.status} | ${error}`);
        }));
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>angular</category>
      <category>interceptorinangular</category>
      <category>meanstack</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Signals in Angular – How to Write More Reactive Code</title>
      <dc:creator>Omama Aslam</dc:creator>
      <pubDate>Mon, 23 Oct 2023 06:03:26 +0000</pubDate>
      <link>https://dev.to/omamaaslam/signals-in-angular-how-to-write-more-reactive-code-3p90</link>
      <guid>https://dev.to/omamaaslam/signals-in-angular-how-to-write-more-reactive-code-3p90</guid>
      <description>&lt;p&gt;An exciting new feature is coming to Angular: signals! Signals provide a new way for our code to tell our templates (and other code) that our data has changed. This improves Angular's change detection, which also improves performance, and makes our code more reactive.&lt;/p&gt;

&lt;p&gt;You can try out this powerful new feature now. Signals are available for developer preview in Angular v16, due to be released in May of 2023. You can get early versions of Angular v16 to try it out now. I'll walk through how later in this tutorial.&lt;/p&gt;

&lt;p&gt;Before we jump into the details of the "what?" and "how?", let's start with the "why?". Why would you want to use this new signals feature?&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Do We Need Signals?
&lt;/h2&gt;

&lt;p&gt;Let's start with a simple example without the use of signals. Say you are writing code to perform some basic math operations.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 5;
let y = 3;
let z = x + y;
console.log(z);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What does this code log to the console? Yep, it logs out &lt;strong&gt;8&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Some time later in the code, we change the value of x. What does z log out now?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 5;
let y = 3;
let z = x + y;
console.log(z);

x = 10;
console.log(z);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It still logs out &lt;strong&gt;8&lt;/strong&gt;! That's because a value is assigned to &lt;strong&gt;z&lt;/strong&gt; when the expression is first evaluated. The &lt;strong&gt;z&lt;/strong&gt; variable does not react to changes in &lt;strong&gt;x&lt;/strong&gt; or &lt;strong&gt;y&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;But we want our variables to react to changes!&lt;/p&gt;

&lt;p&gt;One of the reasons we use Angular is to build reactive websites, like Figure 1. When the user updates the quantity, the related variables (such as subtotal and tax) should react and adjust the costs. If the user selects to delete an item from the cart, we again want the related variables to react and correctly recalculate the costs.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbxq871nnujoq8uucgdek.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbxq871nnujoq8uucgdek.png" alt="Angular Signal Example" width="708" height="309"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;With signals, our code can be more reactive. Our prior example implemented with signals would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const x = signal(5);
const y = signal(3);
const z = computed(() =&amp;gt; x() + y());
console.log(z()); // 8

x.set(10);
console.log(z()); // 13
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We'll look at this syntax in detail shortly. For now, the code above defines two signals: &lt;strong&gt;x&lt;/strong&gt; and &lt;strong&gt;y&lt;/strong&gt; and gives them initial values of &lt;strong&gt;5&lt;/strong&gt; and &lt;strong&gt;3&lt;/strong&gt;. We then define a computed signal, &lt;strong&gt;z&lt;/strong&gt;, which is the sum of &lt;strong&gt;x&lt;/strong&gt; and &lt;strong&gt;y&lt;/strong&gt;. Since signals provide change notifications, when the &lt;strong&gt;x&lt;/strong&gt; or &lt;strong&gt;y&lt;/strong&gt; signals change, any values computed from those signals will automatically recalculate. This code is now reactive! Nice!&lt;/p&gt;

&lt;p&gt;Computed signals react and recalculate when any of its dependent signals change. If a signal is bound in a template, when the signal changes, Angular's change detection automatically updates any view that reads the signal. And the user sees the changed value.&lt;/p&gt;

&lt;p&gt;So the answer to "why do we need signals?":&lt;/p&gt;

&lt;p&gt;Signals provide more reactivity&lt;br&gt;
Using signals gives us finer control over change detection, which can improve performance.&lt;/p&gt;

&lt;p&gt;Let's dive a bit deeper into what a signal is and how it is used.&lt;/p&gt;
&lt;h2&gt;
  
  
  What Is a Signal?
&lt;/h2&gt;

&lt;p&gt;You can think of a signal as a value plus a change notification. A signal is just a special type of variable that holds a value. But unlike other variables, a signal also provides notification when the variable value changes.&lt;/p&gt;

&lt;p&gt;Think of a normal variable as a shelf, like on the left side of Figure 2. When a value is assigned to the variable, it sits on that shelf. Any code within scope can simply read that variable on the shelf.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqok2eshk59th3i2awr89.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqok2eshk59th3i2awr89.png" alt="Signal in Angular" width="800" height="383"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A signal is more like a box, as shown on the right side of Figure 2. Creating a signal metaphorically creates a box and puts the value inside of that box. The box glows when the value of the signal changes. To read the signal, first open the box using parentheses: x(). Technically speaking, we call the signal's getter function to read the signal.&lt;/p&gt;

&lt;p&gt;We now have the answer to "what is a signal?":&lt;/p&gt;

&lt;p&gt;A signal is a variable + change notification&lt;br&gt;
A signal is reactive, and is called a "reactive primitive"&lt;br&gt;
A signal always has a value&lt;br&gt;
A signal is synchronous&lt;br&gt;
A signal is not a replacement for RxJS and Observables for asynchronous operations, such as http.get&lt;/p&gt;

&lt;p&gt;Where can we use signals?&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Use them in components to track local component state&lt;/li&gt;
&lt;li&gt;Use them in directives&lt;/li&gt;
&lt;li&gt;Use them in a service to share state across components&lt;/li&gt;
&lt;li&gt;Read them in a template to display signal values&lt;/li&gt;
&lt;li&gt;Or use them anywhere else in your code&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Next let's walk through how to create and use signals.&lt;/p&gt;
&lt;h2&gt;
  
  
  How to Create a Signal
&lt;/h2&gt;

&lt;p&gt;To use a signal, you first create one.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;quantity = signal&amp;lt;number&amp;gt;(1);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above syntax creates and initializes a signal using the signal constructor function.&lt;/p&gt;

&lt;p&gt;Optionally, provide a generic type parameter to define the signal's data type. A signal can be a string, number, array, object, or any data type. In many cases, the data type can be inferred and the generic type parameter is unnecessary.&lt;/p&gt;

&lt;p&gt;Pass to the constructor the default value of the signal. A signal always has a value, starting with that default.&lt;/p&gt;

&lt;p&gt;Here are some additional examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;quantity = signal(1);

qtyAvailable = signal([1, 2, 3, 4, 5, 6]);

selectedVehicle = signal&amp;lt;Vehicle&amp;gt;({ 
  id: 1,
  name: 'AT-AT', 
  price: 19416.13
});

vehicles = signal&amp;lt;Vehicle[]&amp;gt;([]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first code line above creates a numeric signal with a default value of 1. Because the default value is a number, the quantity is a signal that holds a number. The generic type parameter isn't needed.&lt;/p&gt;

&lt;p&gt;The second line is a signal that holds an array of numbers. The default provides an array of values 1 through 6. Again, the generic type parameter isn't needed in this case because it can be inferred from the default value.&lt;/p&gt;

&lt;p&gt;The selectedVehicle signal holds a Vehicle object. In this example, the type cannot be inferred, so we specify a generic type parameter of Vehicle.&lt;/p&gt;

&lt;p&gt;The vehicles signal holds an array of Vehicle objects. Its default is an empty array. To strongly type the array, we add a generic type parameter of .&lt;/p&gt;

&lt;p&gt;A signal created with the signal constructor function is writable, so you can set it to a new value, update it based on the current value, or mutate its content. We'll see examples of these operations shortly.&lt;/p&gt;

&lt;p&gt;Once you've created a signal, you may want to read its value.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Read a Signal
&lt;/h2&gt;

&lt;p&gt;Earlier, we represented a signal as a box. Metaphorically speaking, to read a signal's value you must first open the box. You do that by adding parentheses as shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;quantity();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Start with the signal name and follow it with open and closing parentheses. Technically speaking, this calls the signal's getter function. The getter function is created behind the scenes – you won't see it in your code.&lt;/p&gt;

&lt;p&gt;When working with Angular, a common place to read signals is in the template.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;select
    [ngModel]="quantity()"
    (change)="onQuantitySelected($any($event.target).value)"&amp;gt;
  &amp;lt;option *ngFor="let q of qtyAvailable()"&amp;gt;{{ q }}&amp;lt;/option&amp;gt;
&amp;lt;/select&amp;gt;

&amp;lt;div&amp;gt;Vehicle: {{ selectedVehicle().name }}&amp;lt;/div&amp;gt;
&amp;lt;div&amp;gt;Price: {{ selectedVehicle().price }}&amp;lt;/div&amp;gt;
&amp;lt;div [style.color]="color()"&amp;gt;Total: {{ totalPrice() }}&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above template displays a select box for selection of a quantity. The [ngModel] reads the value of the quantity signal, binding to that value.&lt;/p&gt;

&lt;p&gt;The change event binding calls the onQuantitySelected() method in the component.&lt;/p&gt;

&lt;p&gt;The option element uses ngFor to iterate through each array element in the qtyAvailable signal. It reads the signal and creates a select option for each array element.&lt;/p&gt;

&lt;p&gt;Below the select element are three div elements. The first one reads the selectedVehicle signal, then accesses its name property. The second div element reads the selectedVehicle signal, then displays its price property. The last div element reads the totalPrice signal (which we have not yet defined). And it sets the text color to the value from the color signal (which we also have not defined).&lt;/p&gt;

&lt;p&gt;It's important to note that reading a signal always reads the current signal value. The code doesn't have any knowledge of any prior signal values.&lt;/p&gt;

&lt;p&gt;When the user picks a different quantity from the select element, we want to change the value of the quantity signal. That way the quantity signal becomes the "source of truth" for the user's selected quantity. Let's look at how to do that next.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Change the Value of a Signal
&lt;/h2&gt;

&lt;p&gt;The signal set method replaces the value of a signal with a new value. It basically opens the box, removes the current item, and sets in a new item to take its place.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.quantity.set(qty);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A common scenario is to change the signal value based on a user action. For example:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The user selects a new quantity using the select element&lt;/li&gt;
&lt;li&gt;The select element event binding calls the onQuantitySelected() method and passes in the selected quantity&lt;/li&gt;
&lt;li&gt;The user action is handled in that event handler within the component&lt;/li&gt;
&lt;li&gt;The new value is set into the quantity signal.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here is an example event handler:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;onQuantitySelected(qty: number) {
  this.quantity.set(qty);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Whenever the signal is set, the code notifies any consumers that the signal has changed. In this context, a consumer is any code that is interested in receiving change notifications.&lt;/p&gt;

&lt;p&gt;How does the consumer indicate that it's interested in receiving notifications about a particular signal?&lt;/p&gt;

&lt;p&gt;How does the consumer indicate that it's interested in receiving notifications about a particular signal?&lt;/p&gt;

&lt;p&gt;So the act of reading a signal registers the consumer's interest in watching that signal. The Angular team calls this the golden rule of signal components: "change detection for a component will be scheduled when and only when a signal read in the template notifies Angular that it has changed."&lt;/p&gt;

&lt;p&gt;Here is an example to illustrate the process. Let's say that there is some work going on within the method below that needs to adjust the quantity. Maybe if the quantity is 5 or more you get one free, for example. The point is that the quantity signal could change several times within the execution of the method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;onQuantitySelected(qty: number) {
  this.quantity.set(qty);

  this.quantity.set(5);
  this.quantity.set(42);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The quantity is displayed in the template using Angular's binding as shown below. Since the binding reads the quantity signal, the template registers its interest in receiving change notifications.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{{ quantity() }}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the user selects a quantity, the onQuantitySelected() method executes. The code in the method first sets the signal to the user-selected quantity. When the new signal is set, the signal generates a notification. At this point, Angular's change detection is scheduled to run. But it doesn't have an opportunity to run until after the execution of the onQuantitySelected() method.&lt;/p&gt;

&lt;p&gt;The onQuantitySelected() method continues, setting the signal to 5. The signal generates another change notification. Again Angular's change detection is reminded that it needs to run, but it still can't run because the onQuantitySelected() method is still executing. The method then sets the signal to 42 and the process repeats.&lt;/p&gt;

&lt;p&gt;When the onQuantitySelected() method has completed its execution, Angular's change detection can finally run. The template reads the signal, and gets the current value of that signal, which is 42. The template is not aware of any of the prior signal values. The view is then re-rendered, and the new quantity signal value is displayed.&lt;/p&gt;

&lt;p&gt;If you are familiar with RxJS and Observables, signals are quite different. Signals don't emit values like Observables do. And signals don't require a subscription.&lt;/p&gt;

&lt;p&gt;In addition to the set(), there are two other ways to change a signal: update() and mutate().&lt;/p&gt;

&lt;p&gt;The set() method replaces a signal with a new value, metaphorically replacing the contents of the signal box. Pass the new value into the set method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Replace the value
this.quantity.set(qty);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The update() method updates the signal based on its current value. Pass to the update method an arrow function. The arrow function provides the current signal value so you can update it as needed. In the code below, the quantity is doubled.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Update value based on current value
this.quantity.update(qty =&amp;gt; qty * 2);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The mutate() method modifies the content of a signal value, not the signal value itself. Use it with arrays to modify array elements, and objects to modify object properties. In the code below, a vehicle's price is increased by 20%.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.selectedVehicle.mutate(v =&amp;gt; v.price = v.price + (v.price * .20));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How to Define a Computed Signal
&lt;/h2&gt;

&lt;p&gt;Oftentimes we have variables in our code that depend on other variables. For example, the total price for an item is the price for that item times the desired quantity of that item. If the user changes the quantity, we want to change the total price. For that, we use computed signals.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;totalPrice = computed(() =&amp;gt; this.selectedVehicle().price * this.quantity());

color = computed(() =&amp;gt; this.totalPrice() &amp;gt; 50000 ? 'green' : 'blue');

The first line of code above defines a totalPrice computed signal by calling the computed() creation function. The computation function passed into this computed function reads the selectedVehicle and quantity signals. If either signal changes, this computed signal is notified and will update when it is its turn to execute.

The second line of code defines a color computed signal. It sets the color to green or blue depending on the value of the totalPrice signal. The template can bind to this signal to display the appropriate style.

A computed signal is read only. It cannot be modified with set(), update() or mutate().

The value of a computed signal is re-computed when:

1. One or more of its dependent signals is changed.
2. AND the value of the computed signal is read.


## How to Use an Effect
There may be times that you need to run code when a signal changes, and that code has side effects. By side effects I mean code that calls an API or performs another operation not related to the signal. In these cases, you'll use an effect().

For example, you want to debug your signals and log out the signal value each time the code reacts to a change to that signal. Calling console.log() is a side effect.

To define an effect, call the effect() creation function. Pass to the function the operation to perform. This operation is re-executed every time the code reacts to a change in any dependent signal.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;effect(() =&amp;gt; console.log(this.selectedVehicle()));&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
The effect() function can be called within other function. Since the effect sets up a handler of sorts, it is often called in the constructor or other startup code.

Alternatively, an effect can be defined declaratively as shown below:

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;e = effect(() =&amp;gt; console.log(this.selectedVehicle()));&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

An effect should not change the value of any signals. If you need to change a signal based on a change to a dependent signal, use a computed signal instead.


**If you find this post helpful please dont forget to like, and share with your collegues also subscribe so you can get more posts that ehance your knowledge..... Thanks for watching**
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
      <category>angularsignals</category>
      <category>reactiveprogramming</category>
      <category>statemanagment</category>
      <category>angular16</category>
    </item>
    <item>
      <title>A Beginner's Guide to Adding Light/Dark Mode Toggle in Angular Material</title>
      <dc:creator>Omama Aslam</dc:creator>
      <pubDate>Tue, 03 Oct 2023 07:33:00 +0000</pubDate>
      <link>https://dev.to/omamaaslam/a-beginners-guide-to-adding-lightdark-mode-toggle-in-angular-material-47h7</link>
      <guid>https://dev.to/omamaaslam/a-beginners-guide-to-adding-lightdark-mode-toggle-in-angular-material-47h7</guid>
      <description>&lt;p&gt;As the demand for user-friendly web applications continues to rise, implementing a light and dark mode feature has become a popular choice among developers. This feature enhances user experience and accessibility, allowing users to choose a theme that suits their preferences. In this beginner-friendly guide, we'll walk you through the steps to add a light/dark mode toggle button to your Angular application using Angular Material.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;Before we get started, make sure you have the following prerequisites in place:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Node.js and npm: Ensure that Node.js and npm (Node Package Manager) are installed on your system. You can download them from &lt;a href="//Node.js%20and%20npm:%20Ensure%20that%20Node.js%20and%20npm%20(Node%20Package%20Manager)%20are%20installed%20on%20your%20system.%20You%20can%20download%20them%20from%20nodejs.org."&gt;nodejs.org.&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Angular CLI: Install the Angular CLI globally by running &lt;strong&gt;npm install -g @angular/cli&lt;/strong&gt; in your terminal.&lt;/li&gt;
&lt;li&gt;Angular Project: Create a new Angular project using the Angular CLI. If you don't have one yet, you can create it by running &lt;strong&gt;ng new my-angular-app&lt;/strong&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Step 1: Install Angular Material
&lt;/h2&gt;

&lt;p&gt;Angular Material is a UI component library that provides pre-built components for Angular applications. To add Angular Material to your project, use the following Angular CLI command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ng add @angular/material
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;During the installation process, you'll have the option to select a pre-built theme or create a custom theme. Choose the option that best fits your project's design requirements.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 2: Create the Theme Toggle Button Component
&lt;/h2&gt;

&lt;p&gt;Next, create a new Angular component to house the light/dark mode toggle button:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ng generate component theme-toggle
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 3: Update the Theme Toggle Component
&lt;/h2&gt;

&lt;p&gt;Now, let's add the necessary code to the** theme-toggle.component.html** and &lt;strong&gt;theme-toggle.component.ts files&lt;/strong&gt; to create the toggle button:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;theme-toggle.component.html:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button mat-icon-button (click)="toggleTheme()"&amp;gt;
  &amp;lt;mat-icon&amp;gt;{{ isDarkMode ? 'wb_sunny' : 'nights_stay' }}&amp;lt;/mat-icon&amp;gt;
&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;theme-toggle.component.ts:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Component } from '@angular/core';
import { ThemeService } from '../theme.service';

@Component({
  selector: 'app-theme-toggle',
  templateUrl: './theme-toggle.component.html',
  styleUrls: ['./theme-toggle.component.css'],
})
export class ThemeToggleComponent {
  isDarkMode: boolean;

  constructor(private themeService: ThemeService) {
    this.isDarkMode = this.themeService.isDarkMode();
  }

  toggleTheme() {
    this.isDarkMode = !this.isDarkMode;
    this.themeService.setDarkMode(this.isDarkMode);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 4: Create a Theme Service
&lt;/h2&gt;

&lt;p&gt;To manage the application's theme state, create a service called &lt;strong&gt;ThemeService&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ng generate service theme
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the &lt;strong&gt;theme.service.ts&lt;/strong&gt; file, add methods to get and set the theme:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;theme.service.ts:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class ThemeService {
  private darkMode = false;

  isDarkMode() {
    return this.darkMode;
  }

  setDarkMode(isDarkMode: boolean) {
    this.darkMode = isDarkMode;
    if (isDarkMode) {
      document.body.classList.add('dark-theme');
    } else {
      document.body.classList.remove('dark-theme');
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 5: Define CSS for Dark Theme
&lt;/h2&gt;

&lt;p&gt;In your project's global styles file (usually src/styles.css), define CSS styles for the dark theme. For example:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;styles.css:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* Dark Theme Styles */
.dark-theme {
  background-color: #121212;
  color: #ffffff;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 6: Use the Theme Toggle Button
&lt;/h2&gt;

&lt;p&gt;In your main application template &lt;strong&gt;(app.component.html)&lt;/strong&gt;, include the &lt;strong&gt;&lt;/strong&gt; tag to add the theme toggle button to your app's interface:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;app.component.html:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div class="app-container"&amp;gt;
  &amp;lt;app-theme-toggle&amp;gt;&amp;lt;/app-theme-toggle&amp;gt;
  &amp;lt;!-- Other content of your app --&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 7: Run Your Application
&lt;/h2&gt;

&lt;p&gt;You're all set! To see your light/dark mode toggle button in action, run your Angular application using the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ng serve
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Visit &lt;strong&gt;&lt;a href="http://localhost:4200" rel="noopener noreferrer"&gt;http://localhost:4200&lt;/a&gt;&lt;/strong&gt; in your web browser to interact with your app and switch between light and dark modes using the toggle button.&lt;/p&gt;

&lt;p&gt;Congratulations! You've successfully added a light/dark mode toggle button to your Angular application using Angular Material. This feature enhances the user experience and allows users to customize their viewing experience according to their preferences.&lt;/p&gt;

&lt;p&gt;Feel free to customize the styles, icons, and themes to match your application's design. Happy coding!&lt;/p&gt;

</description>
      <category>toggletheme</category>
      <category>angularmaterial</category>
      <category>uiuxdeveloper</category>
      <category>singlepageapplication</category>
    </item>
    <item>
      <title>Angular 16 Google Social Login or Sign In Tutorial</title>
      <dc:creator>Omama Aslam</dc:creator>
      <pubDate>Wed, 13 Sep 2023 08:46:08 +0000</pubDate>
      <link>https://dev.to/omamaaslam/angular-16-google-social-login-or-signin-tutorial-46ka</link>
      <guid>https://dev.to/omamaaslam/angular-16-google-social-login-or-signin-tutorial-46ka</guid>
      <description>&lt;p&gt;Angular Google social login tutorial, In this extensive tutorial, you will discover how to create Google social login in an angular application using the angularx-social-login package.&lt;/p&gt;

&lt;p&gt;Social login is the way of accessing or signing in to the third-party app without creating a new login account, especially using the current information gathered from social media platforms like Google, Twitter, Facebook, etc.&lt;/p&gt;

&lt;p&gt;In this angular google login example, we will show you how to implement google signin into Angular application using Google developer account (client id and key) in conjugation with angularx social login plugin.   &lt;/p&gt;

&lt;p&gt;The angularx-social-login library provides a social login/signin and authentication module. To implement google login or signin into angular, you must have a client id and secret. You can get a client id and secret only after creating a Google project or app inside the Google developer console.&lt;/p&gt;

&lt;h2&gt;
  
  
  Angular 16 Login with Google Example
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Step 1:&lt;/strong&gt; Install New Angular App&lt;br&gt;
&lt;strong&gt;Step 2:&lt;/strong&gt; Install Bootstrap UI&lt;br&gt;
&lt;strong&gt;Step 3:&lt;/strong&gt; Get Google Client ID &amp;amp; Secret&lt;br&gt;
&lt;strong&gt;Step 4:&lt;/strong&gt; Install Angular Social Login Package&lt;br&gt;
&lt;strong&gt;Step 5:&lt;/strong&gt; Register Social Login Modules&lt;br&gt;
&lt;strong&gt;Step 6:&lt;/strong&gt; Integrate Google Social Login in Angular&lt;br&gt;
&lt;strong&gt;Step 7:&lt;/strong&gt; Run Angular Application&lt;/p&gt;

&lt;h2&gt;
  
  
  Install New Angular Project
&lt;/h2&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

ng new ng-demo-app


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Go inside the project folder by entering the command below : &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

cd ng-demo-app


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Install Bootstrap UI
&lt;/h2&gt;

&lt;p&gt;To make the google login auth template, you need bootstrap; hence install it now with below command:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

npm i bootstrap


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, place the Bootstrap module CSS path in the styles array:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

"styles": [
     "node_modules/bootstrap/dist/css/bootstrap.min.css",
     "src/styles.scss"
]


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Get Google Client ID and Secret
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Step 1:&lt;/strong&gt; You have to create the latest project similarly shown as given below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcymjfp1iob8h6tc0yp57.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcymjfp1iob8h6tc0yp57.jpeg" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2:&lt;/strong&gt; Define the project name like it is declared on the following screenshot:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnw2d3lwp1262gj7iy8ul.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnw2d3lwp1262gj7iy8ul.jpeg" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3:&lt;/strong&gt; Further, you see internal and external user type within the OAuth consent screen; hence select External from the options:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe4dmz0xsqm8t32lyq28c.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe4dmz0xsqm8t32lyq28c.jpeg" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4:&lt;/strong&gt; Additionally, on the subsequent screen, you need to define the site or privacy policy url:&lt;br&gt;
&lt;strong&gt;Step 5:&lt;/strong&gt; Next, click on the Create Credentials, choose OAuth client ID from the options:&lt;br&gt;
&lt;strong&gt;Step 6:&lt;/strong&gt; On top of that, choose Web application from the application type options. Right after, provide the app name, define your URL app under the Authorized JavaScript origins options.&lt;br&gt;
Home  »  Angular   »   Angular 16 Google Social Login or Signin Tutorial&lt;br&gt;
Angular 16 Google Social Login or Signin Tutorial&lt;br&gt;
Last updated on: August 20, 2023 by Digamber&lt;/p&gt;

&lt;p&gt;Angular Google social login tutorial, In this extensive tutorial, you will discover how to create Google social login in an angular application using the angularx-social-login package.&lt;/p&gt;

&lt;p&gt;Social login is the way of accessing or signing in to the third-party app without creating a new login account, especially using the current information gathered from social media platforms like Google, Twitter, Facebook, etc.&lt;/p&gt;

&lt;p&gt;In this angular google login example, we will show you how to implement google signin into Angular application using Google developer account (client id and key) in conjugation with angularx social login plugin.&lt;/p&gt;

&lt;p&gt;The angularx-social-login library provides a social login/signin and authentication module for Angular 9+.&lt;/p&gt;

&lt;p&gt;It is not limited to login with Google and immaculately supports authentication with Facebook, Amazon, including VK. Nonetheless, if you have some other providers, then fret not; you can also build social login with another provider.&lt;/p&gt;

&lt;p&gt;To implement google login or signin into angular, you must have a client id and secret. You can get a client id and secret only after creating a Google project or app inside the Google developer console.&lt;/p&gt;

&lt;p&gt;You will also be taught to create and get a client id and secret in conjugation with the google developer console.&lt;/p&gt;

&lt;p&gt;Angular 16 Login with Google Example&lt;br&gt;
Step 1: Install New Angular App&lt;br&gt;
Step 2: Install Bootstrap UI&lt;br&gt;
Step 3: Get Google Client ID &amp;amp; Secret&lt;br&gt;
Step 4: Install Angular Social Login Package&lt;br&gt;
Step 5: Register Social Login Modules&lt;br&gt;
Step 6: Integrate Google Social Login in Angular&lt;br&gt;
Step 7: Run Angular Application&lt;br&gt;
Install New Angular Project&lt;br&gt;
Commence the first step by installing the new angular project:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

ng new ng-demo-app


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Including, get into the project’s root:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

cd ng-demo-app


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Install Bootstrap UI&lt;br&gt;
To make the google login auth template, you need bootstrap; hence install it now with below command:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

npm i bootstrap


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, place the Bootstrap module CSS path in the styles array:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

"styles": [
     "node_modules/bootstrap/dist/css/bootstrap.min.css",
     "src/styles.scss"
]


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Get Google Client ID and Secret&lt;br&gt;
This step profoundly explains how to get the Google client id and secret. Thereupon, head over to the Google developer console and follow the suggested steps respectively:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1:&lt;/strong&gt; You have to create the latest project similarly shown as given below:&lt;br&gt;
&lt;strong&gt;Step 2:&lt;/strong&gt; Define the project name like it is declared on the following screenshot:&lt;br&gt;
&lt;strong&gt;Step 3:&lt;/strong&gt; Further, you see internal and external user type within the OAuth consent screen; hence select External from the options:&lt;br&gt;
&lt;strong&gt;Step 4:&lt;/strong&gt; Additionally, on the subsequent screen, you need to define the site or privacy policy url:&lt;br&gt;
&lt;strong&gt;Step 5:&lt;/strong&gt; Next, click on the Create Credentials, choose OAuth client ID from the options:&lt;br&gt;
choose OAuth client ID&lt;br&gt;
&lt;strong&gt;Step 6:&lt;/strong&gt; On top of that, choose Web application from the application type options. Right after, provide the app name, define your URL app under the Authorized JavaScript origins options. For instance, we are working on localhost; consequently, we defined the localhost URL:&lt;br&gt;
&lt;strong&gt;Step 7:&lt;/strong&gt; Ultimately, the OAuth client popup manifests on the screen, from here you can copy Your Client Id or client secret.&lt;/p&gt;

&lt;h2&gt;
  
  
  Install Angular Social Login Package
&lt;/h2&gt;

&lt;p&gt;Generically, now we have to use the NPM command to install the &lt;strong&gt;angularx-social-login&lt;/strong&gt; package. This is the most quintessential plugin which allows building google social signin in angular application.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

npm install @abacritt/angularx-social-login --legacy-peer-deps


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Register Social Login Modules in App Module
&lt;/h2&gt;

&lt;p&gt;Open app.module.ts file, import ReactiveFormsModule, SocialLoginModule, SocialAuthServiceConfig and GoogleLoginProvider modules.&lt;/p&gt;

&lt;p&gt;Also, inject these modules in imports as well as inside the providers’ array.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
import {
  SocialLoginModule,
  SocialAuthServiceConfig,
} from '@abacritt/angularx-social-login';
import { GoogleLoginProvider } from '@abacritt/angularx-social-login';
@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, ReactiveFormsModule, SocialLoginModule],
  providers: [
    {
      provide: 'SocialAuthServiceConfig',
      useValue: {
        autoLogin: false,
        providers: [
          {
            id: GoogleLoginProvider.PROVIDER_ID,
            provider: new GoogleLoginProvider('Google-Client-ID-Goes-Here'),
          },
        ],
      } as SocialAuthServiceConfig,
    },
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We imported GoogleLoginProvider from the ‘angularx-social-login’ package, albeit you can also import the other social platforms in conjunction with building social login in angular.&lt;/p&gt;

&lt;p&gt;Moreover, the Google client id has to be injected within the GoogleLoginProvider() provider.&lt;/p&gt;

&lt;h2&gt;
  
  
  Integrate Google Social Login in Angular
&lt;/h2&gt;

&lt;p&gt;In this step, we will do the most crucial task of this tutorial, which is to implement angular google social login.&lt;/p&gt;

&lt;p&gt;Hence, app.component.html template file and add the following code.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;div class="container" style="max-width: 550px"&amp;gt;
  &amp;lt;h2 class="text-center mb-5"&amp;gt;Angular Login with Google&amp;lt;/h2&amp;gt;
  &amp;lt;div *ngIf="isLoggedin === false"&amp;gt;
    &amp;lt;div&amp;gt;
      &amp;lt;button type="button" (click)="loginWithGoogle()" class="btn btn-danger"&amp;gt;Login with Google&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  &amp;lt;/div&amp;gt;
  &amp;lt;div *ngIf="isLoggedin === true"&amp;gt;
    &amp;lt;div class="form-group"&amp;gt;
      &amp;lt;label&amp;gt;First Name&amp;lt;/label&amp;gt;
      &amp;lt;input type="text" class="form-control" [value]="socialUser.firstName" id="firstname" readonly&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;div class="form-group"&amp;gt;
      &amp;lt;label&amp;gt;Last Name&amp;lt;/label&amp;gt;
      &amp;lt;input type="text" class="form-control" [value]="socialUser.lastName" id="lastname" readonly&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;div class="form-group"&amp;gt;
      &amp;lt;label&amp;gt;Email&amp;lt;/label&amp;gt;
      &amp;lt;input type="text" class="form-control" [value]="socialUser.email" id="email" readonly&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;button type="button" (click)="logOut()" class="btn btn-primary"&amp;gt;Log Out&amp;lt;/button&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Open and update the app.component.ts template.&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&lt;p&gt;import { Component, OnInit } from '@angular/core';&lt;br&gt;
import { FormBuilder, FormGroup, Validators } from '@angular/forms';&lt;br&gt;
import {&lt;br&gt;
  SocialAuthService,&lt;br&gt;
  GoogleLoginProvider,&lt;br&gt;
  SocialUser,&lt;br&gt;
} from '@abacritt/angularx-social-login';&lt;br&gt;
@Component({&lt;br&gt;
  selector: 'app-root',&lt;br&gt;
  templateUrl: './app.component.html',&lt;br&gt;
  styleUrls: ['./app.component.scss'],&lt;br&gt;
})&lt;br&gt;
export class AppComponent implements OnInit {&lt;br&gt;
  loginForm!: FormGroup;&lt;br&gt;
  socialUser!: SocialUser;&lt;br&gt;
  isLoggedin?: boolean;&lt;br&gt;
  constructor(&lt;br&gt;
    private formBuilder: FormBuilder,&lt;br&gt;
    private socialAuthService: SocialAuthService&lt;br&gt;
  ) {}&lt;br&gt;
  ngOnInit() {&lt;br&gt;
    this.loginForm = this.formBuilder.group({&lt;br&gt;
      email: ['', Validators.required],&lt;br&gt;
      password: ['', Validators.required],&lt;br&gt;
    });&lt;br&gt;
    this.socialAuthService.authState.subscribe((user) =&amp;gt; {&lt;br&gt;
      this.socialUser = user;&lt;br&gt;
      this.isLoggedin = user != null;&lt;br&gt;
      console.log(this.socialUser);&lt;br&gt;
    });&lt;br&gt;
  }&lt;br&gt;
  loginWithGoogle(): void {&lt;br&gt;
    this.socialAuthService.signIn(GoogleLoginProvider.PROVIDER_ID);&lt;br&gt;
  }&lt;br&gt;
  logOut(): void {&lt;br&gt;
    this.socialAuthService.signOut();&lt;br&gt;
  }&lt;br&gt;
}&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Run Angular Application&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;Ultimately, social login integrated into angular, and now you need to start the angular development server to test the app:&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&lt;p&gt;ng serve --open&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Conclusion&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;Eventually, the angular login with Google tutorial is over; in this tutorial, we extensively explained how to signin with google in angular using the Google client id.&lt;/p&gt;

&lt;p&gt;I hope you will love this step by step guide and share it with others.&lt;/p&gt;

</description>
      <category>angular16</category>
      <category>sociallogin</category>
      <category>angularblogs</category>
      <category>omamablogs</category>
    </item>
    <item>
      <title>ElementRef in Angular | How to use it</title>
      <dc:creator>Omama Aslam</dc:creator>
      <pubDate>Thu, 31 Aug 2023 11:56:30 +0000</pubDate>
      <link>https://dev.to/omamaaslam/elementref-in-angular-how-to-use-it-5039</link>
      <guid>https://dev.to/omamaaslam/elementref-in-angular-how-to-use-it-5039</guid>
      <description>&lt;p&gt;Angular ElementRef is a wrapper around a native DOM element (HTML element) object. It contains the property nativeElement, which holds the reference to the underlying DOM object. We can use it to manipulate the DOM. We use the ViewChild to get the ElementRef of an HTML element in the component class. Angular also inject ElementRef of the Host element of the component or directive when you request for it in the constructor. In this tutorial, let us explore how to use ElementRef to get the reference of an HtmlElement &amp;amp; manipulate the DOM in Angular Applications.&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;Table Of Content: *&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;ElementRef&lt;/li&gt;
&lt;li&gt;Getting ElementRef in Component Class&lt;/li&gt;
&lt;li&gt;ElementRef Example&lt;/li&gt;
&lt;li&gt;ElementRef in Custom Directive&lt;/li&gt;
&lt;li&gt;ElementRef &amp;amp; XSS Injection Attack&lt;/li&gt;
&lt;li&gt;Refrence&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  ElementRef
&lt;/h2&gt;

&lt;p&gt;The DOM objects are created and maintained by the Browser. They represent the structure and content of the Document. In a Vanilla JavaScript code, we access these DOM objects to manipulate the View. We can create and build documents, navigate their structure, and add, modify, or delete elements and content.&lt;/p&gt;

&lt;p&gt;Angular provides a lot of tools &amp;amp; techniques to manipulate the DOM. We can add/remove components. It provides a lot of directives like Class Directive or Style directive. to Manipulate their styles etc.&lt;/p&gt;

&lt;p&gt;We may still need to access the DOM element on some occasions. This is where the ElementRef comes into the picture.&lt;/p&gt;

&lt;h2&gt;
  
  
  Getting ElementRef in Component Class
&lt;/h2&gt;

&lt;p&gt;To manipulate the DOM using the ElementRef, we need to get the reference to the DOM element in the component/directive.&lt;/p&gt;

&lt;p&gt;embed To get the reference to DOM elements in the component&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create a template reference variable for the element in the component/directive.&lt;/li&gt;
&lt;li&gt;Use the template variable to inject the element into component class using the ViewChild or ViewChildren.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;To get the DOM element hosting the component/directive&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Ask for ElementRef in the constructor (Angular Dependency injection), the Angular will inject the reference element hosting the component/directive.
For Example, in the following code, the variable hello refers to the HTML element div.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div #hello&amp;gt;Hello Angular&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;hello is the Template Reference variable, which we can use in the Template.&lt;/p&gt;

&lt;p&gt;In the Component class, we use the ViewChild to inject the hello element. The Angular injects the hello as a type of ElementRef.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@ViewChild('hello', { static: false }) divHello: ElementRef;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Read token
&lt;/h2&gt;

&lt;p&gt;Consider the following example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;input #nameInput [(ngModel)]="name"&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The nameInput Template Reference Variable now binds to the input element. But at the same time, we have ngModel directive applied to it.&lt;/p&gt;

&lt;p&gt;Under such circumstance, we can use the read token to let angular know that we need ElementRef reference as shown below&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//ViewChild returns ElementRef i.e. input HTML Element

@ViewChild('nameInput',{static:false, read: ElementRef}) elRef;


//ViewChild returns NgModel associated with the nameInput
@ViewChild('nameInput',{static:false, read: NgModel}) inRef;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  ElementRef Example
&lt;/h2&gt;

&lt;p&gt;Once we have the ElementRef , we can use the nativeElement property to manipulate the DOM as shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Component,ElementRef, ViewChild, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-root',
  template:  '&amp;lt;div #hello&amp;gt;Hello&amp;lt;/div&amp;gt;'
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {

 @ViewChild('hello', { static: false }) divHello: ElementRef;

 ngAfterViewInit() {
   this.divHello.nativeElement.innerHTML = "Hello Angular";
 }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can manipulate the DOM very easily.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  ngAfterViewInit() {
    this.divHello.nativeElement.innerHTML = "Hello Angular";
    this.divHello.nativeElement.className="someClass";
    this.divHello.nativeElement.style.backgroundColor="red";
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  ElementRef in Custom Directive
&lt;/h2&gt;

&lt;p&gt;One of the use case for ElementRef is the Angular directive. We learned how to create a custom directive in Angular. The following is the code for the ttClass custom attribute directive.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Directive, ElementRef, Input, OnInit } from '@angular/core'

@Directive({
  selector: '[ttClass]',
})
export class ttClassDirective implements OnInit {

  @Input() ttClass: string;

  constructor(private el: ElementRef) {
  }

  ngOnInit() {
    this.el.nativeElement.classList.add(this.ttClass);
  }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that we are injecting the ElementRef in the constructor. Whenever we ask for the ElementRef in the constructor, the Angular will inject the reference to the host DOM element of the directive.&lt;/p&gt;

&lt;h2&gt;
  
  
  ElementRef &amp;amp; XSS Injection Attack
&lt;/h2&gt;

&lt;p&gt;Improper use of ElementRef can result in an XSS Injection attack. For Example in the following code, we are injecting a script using the elementRef. When the component containing such code runs, the script is executed&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;constructor(private elementRef: ElementRef) {
    const s = document.createElement('script');
    s.type = 'text/javascript';
    s.textContent = 'alert("Hello World")';
    this.elementRef.nativeElement.appendChild(s);
 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Reference
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://angular.io/api/core/ElementRef" rel="noopener noreferrer"&gt;ElementRef&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If you liked this, click the ❤️ below so other people will see this here on Medium. Please don’t forget to like, subscribe and comments.&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>angular</category>
      <category>javascript</category>
      <category>elementrefinangular</category>
      <category>angularmagic</category>
    </item>
    <item>
      <title>How to host Angular + Express (API) on firebase free hosting.</title>
      <dc:creator>Omama Aslam</dc:creator>
      <pubDate>Wed, 30 Aug 2023 06:30:08 +0000</pubDate>
      <link>https://dev.to/omamaaslam/how-to-host-angular-express-api-on-firebase-free-hosting-3276</link>
      <guid>https://dev.to/omamaaslam/how-to-host-angular-express-api-on-firebase-free-hosting-3276</guid>
      <description>&lt;p&gt;In this story, I am going to talk about firebase hosting for Angular and Express API. I have considered MEAN stack here.&lt;/p&gt;

&lt;p&gt;In this article, I will assume the application is ready with SSR and express API is ready.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;What is Firebase Hosting?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Firebase hosting is a Google hosting service which provides static web content to the user in a secure, fast, free and easy way.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Why Firebase Hosting?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Most of the web hosting will charge you or will be slow if they are free, also you have to pay extra for getting an SSL certificate to convert your website to a secure one with https.&lt;/p&gt;

&lt;p&gt;Firebase hosting is free. So, it won’t cost you anymore. It by default provides SSL certificate and offers an impressive speed across multiple geographic locations without the need for a separate CDN on top.&lt;/p&gt;

&lt;h2&gt;
  
  
  Requirements
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Google Account:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I believe you might already have a Gmail account, which is enough. If not create one.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Firebase-CLI:&lt;/strong&gt;&lt;br&gt;
Before you can install the Firebase CLI, you will need to install Node.js on your machine.&lt;/p&gt;

&lt;p&gt;Once you’ve installed NodeJs, you can install the Firebase CLI using npm (the Node Package Manager) by running the following command:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

npm install -g firebase-tools


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Lets get started :)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Creating firebase project&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Go to (&lt;a href="https://firebase.google.com/" rel="noopener noreferrer"&gt;https://firebase.google.com/&lt;/a&gt;) and sign in with your Google account&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgcf44aderw1xjy8j0c5l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgcf44aderw1xjy8j0c5l.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;then create new project, enter your project name (firebase-express-demo in my case)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftrecmzkrqxbl8p33yvls.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftrecmzkrqxbl8p33yvls.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Firebase Login&lt;/strong&gt;&lt;br&gt;
Now come back to the command line and go to your project folder&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

cd firebase-express-demo


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;First we have to login into firebase from command line. Type in the following command.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

firebase login


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;It will take you to the sign-in page in the browser, once you’ve successfully logged in it will show you something like this.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Setup firebase in project&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To setup firebase in your existing project you have to perform below task.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create firebase.json to root of your project (You can read more about firebase.json(&lt;a href="https://firebase.google.com/docs/hosting/full-config" rel="noopener noreferrer"&gt;https://firebase.google.com/docs/hosting/full-config&lt;/a&gt;) &lt;/li&gt;
&lt;li&gt;Optional, Create .firebaserc (This may useful, if you have multiple environments and multiple websites)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is how my firebase.json and .firebaserc looks like &lt;br&gt;
(&lt;a href="https://github.com/erashu212/firebase-express-demo/blob/master/firebase.json" rel="noopener noreferrer"&gt;https://github.com/erashu212/firebase-express-demo/blob/master/firebase.json&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;We will use firebase functions and http events to route express API.&lt;/p&gt;

&lt;p&gt;In my firebase.json, there is a section of hosting which is having public, rewrites and functions property.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;“public”&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It tells firebase to make that folder publicly accessible. This should be the folder which are meant to be available for end user. In my case, I have marked dist as public (this dist folder is generated using angular-cli)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;“rewrites”&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As the name suggest, It is a re-writer which trigger the function on hit of specified source.&lt;/p&gt;

&lt;p&gt;In my case, on hit of public domain (&lt;a href="https://firebase-express-demo.firebaseapp.com/" rel="noopener noreferrer"&gt;https://firebase-express-demo.firebaseapp.com/&lt;/a&gt;), it will trigger the function expressApp&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;“functions”&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This block is used to expose your https events and firebase functions. In my case I have stated where expressApp function can be found.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;"source": "&amp;lt;dir_name&amp;gt;", in my case it is functions folder&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In this project, I have created two sub-folders under root folder.&lt;/p&gt;

&lt;p&gt;“server ”: This directory will keep all express related stuff.&lt;/p&gt;

&lt;p&gt;“functions ”:This will keep code and structure for firebase hosting.&lt;/p&gt;

&lt;p&gt;Firebase deploy requires all the dependencies to be listed under functions folder package.json.&lt;/p&gt;

&lt;p&gt;The dependencies defined in package.json are going to be installed freshly during deployment.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 5: Deployment&lt;/strong&gt;&lt;br&gt;
In this demo project, I have written a small script which will copy the dist, server and dependencies to “functions” directory.&lt;/p&gt;

&lt;p&gt;You can see the scripts here&lt;/p&gt;

&lt;p&gt;(&lt;a href="https://github.com/erashu212/firebase-express-demo/blob/master/index.js" rel="noopener noreferrer"&gt;https://github.com/erashu212/firebase-express-demo/blob/master/index.js&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;When we say&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

firebase deploy


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;it is going to deploy the folder mentioned in firebase.json and functions defined under “functions” sections&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Congratulations! your website is now live,&lt;/strong&gt; you can check by going to url which is provided in the command line in my case it is (&lt;a href="https://fir-demo-63781.firebaseapp.com/" rel="noopener noreferrer"&gt;https://fir-demo-63781.firebaseapp.com/&lt;/a&gt;)&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;If you liked this, click the ❤️ below so other people will see this here on Medium. Please don’t forget to like, subscribe and comments.&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>angular</category>
      <category>express</category>
      <category>mongodb</category>
      <category>firebase</category>
    </item>
  </channel>
</rss>
