AngularJS's Articles

AngularJS is a JavaScript-based open-source front-end web framework mainly maintained by Google and by a community of individuals and corporations to address many of the challenges encountered in developing single-page applications.

Angular 12 Copy to Clipboard Example Tutorial
There are so many JavaScript plugin available to Copy text from div or input box. Copy to clipboard is useful copy links, coupons, code, or password. This way, users don't need to type text or select and copy. User only need to click copy button only. This gives user smooth experience. In this tutorial, we will implement copy to clipboard feature into Angular project. We will go through step by step from the scratch. The tutorial follows below steps: We assume that you have already installed all required packages and complete Angular environment setup. Step 1: Create new Angular application Step 2: Install ngx-clipboard module Step 3: Import ClipboardModule in App Module Step 4: Use ngxClipboard directive into HTML Step 5: Start Angular server and test So let's start from creating new Angular application. Step 1: Create new Angular application After installed Angular CLI package, we can create new Angular application using following ng command into Terminal or Command Prompt. ng new clipboard It will ask few questions like install router module, default stylesheet etc. You can give answer according to your requirement. Next change Terminal's working directory to application root. cd clipboard Step 2: Install ngx-clipboard module In this step, we will install ngx-clipboard package using npm. This will provide clipboard directive which helps to copy and paste the text into Angular application. npm install ngx-clipboard --save Step 3: Import ClipboardModule in App Module After we installed ngx-clipboard module, we need to import ClipboardModule in AppModule. Open app.module.ts file and import ClipboardModule and also add in imports array. import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ClipboardModule } from 'ngx-clipboard'; @NgModule({   declarations: [     AppComponent   ],   imports: [     BrowserModule,     AppRoutingModule,     ClipboardModule   ],   providers: [],   bootstrap: [AppComponent] }) export class AppModule { } Step 4: Use ngxClipboard directive into HTML There are several ways to copy text. We will see input box and using ClipboardService method. You can refer official site to learn more ways. Copy text from textbox Now we are ready to use ngxClipboard directive into HTML template. We will create input box and pass its value to ngxClipboard directive. Open app.component.html file from app directory and change HTML code to below. <!doctype html> <html>   <head>     <title>Copy to clipboard</title>     <link href="" rel="stylesheet">   </head>   <body>     <div class="container" #container>       <div class="mt-3">         <div class="mb-3">           <label for="text" class="form-label">Copy to Clipboard</label>           <input type="text" #text class="form-control w-25" placeholder="Text message">         </div>       </div>       <button class="btn btn-primary" [ngxClipboard]="text">Copy text</button>     </div>   </body> </html> Copy using ClipboardService for dynamic copy data If you want to copy dynamic data from the component class. You need to use copy() method from ClipboardService class. Open app.component.ts and import ClipboardService. You will also need to create instance of the class. import { Component } from '@angular/core'; import { ClipboardService } from 'ngx-clipboard'; @Component({   selector: 'app-root',   templateUrl: './app.component.html',   styleUrls: ['./app.component.css'] }) export class AppComponent {   title = 'This texst will be copied';   constructor(private clipboardService: ClipboardService) { }   copyText() {     this.clipboardService.copyFromContent(this.title)   } } We have also created copyText() method which will call on button click. In the app.component.html file, create a button with click event. The button will trigger copyText() method from component. <!doctype html> <html>   <body>     <div class="container m-3">       <button (click)="copyText()">Copy text</button>     </div>   </body> </html> Step 5: Start Angular server and test That's it. Now run Angular server using below ng command into Terminal. ng serve --open This will start Angular server and open http://localhost:4200/ url into default browser. Now type into text box and click Copy button. This will copy text from the input box. Conclusion In this article, we have used ngx-clipboard module and used it to copy text from input box or from the component. I hope you have liked this article.
Angular Advance Interview Questions 2021
Angular is a very popular name among web developers and programmers. There is no doubt, and Angular is one of the most used client-side frameworks.  Angular is a javascript framework that provides developers with efficient implements to build better web applications. It is a very utilizable framework for designing robust web applications expeditiously, and Angular withal enables developers to test and organize the JS code. Due to the fact that Angular is such a popular framework, it is frequently asked about in developer interviews. Thus if you optate to get a development job and are going to fight an interview for identically tantamount, its time you refine your erudition about Angular.  To avail you accomplish identically tantamount, we are here with the top angular 12 interview questions along with their answers. Check out latest Angular Tutorials. Why only Angular 12?  Because Angular’s latest version is Angular so most of our questions will be based on Angular, and few questions will be based on older AngularJS version.  Read all the questions and their answers carefully and get ready to win your next interview. Here we go- 1. Give a brief introduction to Angular.  Angular is a web application framework that is typescript-based and is maintained by Google. It enables developers to create robust web applications or even mobile apps by providing tools to build the frontend. These functionalities and tools that Angular offers are easy to use. It is an open-source framework.  2. Who is Misko Hevery? Misko Hevery is often called the father of Angular. He is an agile coach at Google. He studied at Santa Clara University and lived in CA.  3. Name a few features of Angular? Although Angular offers a variety of features and functionalities to facilitate web application development, some of the well-known features are dependency injection, declarative templates, end-to-end tooling, etc. 4. What do you mean by components in Angular? Components are utilized to build the UI of the application; thus, components control the look and feel of the Angular Application. So basically, Components are typescript classes. These classes interact with HTML CSS to manage the UI. 5. How to create and configure components in Angular.  To create components in Angular, @Component decorator is utilized. This @Component decorator is a fraction of the @angular/core module. To configure a component in Angular, we need to pass data in them.   6. What is Angular and how it is different from Angular? Angular’s latest version is called Angular. This version of Angular is more efficient, and development using Angular has just got better with Angular.  7. Explain the difference between Angular and AngularJs.  Angular is a javascript framework that allows developers to build efficient applications using built-in tools and features.  Angular is an upgrade to AngularJs, and thus it is a better framework for application development.  Angular is faster to develop applications than Angularjs.  Angular uses javascript to build an application and, on the other hand, AngularJs utilized typescript.  Angular is mobile-friendly, but Angularjs was not.  8. Why do people use Angular?  Using Angular for application or website development comes with certain advantages. It provides a wide array of tools and functionalities to build scalable websites fast and efficiently. It is a reliable framework for development chores as Google manages it. Further advantages that make people use Angular are as follows- Angular works on MVC patten architecture and two-way binding is supported by Angular.  Angular also supports validations.  Both Angular and static templates are favoured in Angular.  Angular supports Restful API and enables developers to create custom directives.  Angular provides many features like animation.  It supports dependency injects and client and server communication.  9. Name some common or popular Angular features.  Though Angular offers a wide range of features to facilitate web application development, some notable features are as follows-  Templates Dependency Injection (DI) Directive Code splitting Child-Parent Relationship Data Binding Localization Validation Testing Model View Controller (MVC) 10. Why is typescript useful? Typescript is useful in a variety of ways like it improves consistency, productivity, modularity, and ease to catch errors.  11. On what port Angular runs? Angular runs on 4200 port, but it could be configured.  12. Explain Modules in Angular? A module incorporates single or multiple components, but they have nothing to do with HTML. Modules are used for declaring what components of different modules can utilize components. It also declares which class the dependency injector would inject. It gives rise to modularity in your application by managing the components.  13. Name the latest version of Angular in use? The latest version of Angular in use at present is Angular.  14. Explain MVC architecture.  Angular follows the MVC architecture. MVC is the abbreviation for the model view controller. This MVC architecture is a simplified architecture to build modern UI. This architecture provides some of the essential elements you would need to build UI’s for desktop, mobile or even web applications. MVC is the standard architecture being used today to build robust applications.  15. Can you explain the SPA? SPA is the abbreviation for a single page application. This type of web improves the speed and overall digital experience by dynamically reloading selected page elements in line with user interactions. Thus this avoids the need for fetching the elements altogether from the server.  16. Explain AOT.  AOT compilation or the abbreviation for ahead of time compilation is the process of internal compilation of code. The compiler compiles typescript code and converts the typescript code to javascript code. This occurs once per event per user.  17. What do you know about Angular material? Angular material is one of the Angular user interface component libraries. Since it is a UI component library, it allows developers to build attractive web pages that are fully operative and also consistent. The library follows modern principles for web design.  18. Do you know about Angular directives? The directive in Angular is of great help as they enable developers to write new and application-specific HTML syntax. Directives are functions that run when the compiler discovers them in DOM.  19. Name the different types of Directives in Angular? Different type of Angular directives are as follows- Structural Directives Attribute Directives Component Directives 20. What are annotations in Angular? To create an annotation array, we use Angular annotations. They use reflect metadata library as to the metadata set of the class.  21. What are decorators in Angular? Decorators, as the name suggests, are the design patterns. These design patterns are utilized in order to segregate the modification of a class without altering source code.  22. What do you mean by ngOnInit () in Angular? A lifecycle hook called after the initialization of all data-bound properties of a directive has been done by Angular.  23. How will you define ngOnInit ()? It can ve defined as follows: Interface OnInit { ngOnInit() : void } 24. What is service in Angular? Services in Angular are singleton objects. This singleton objects only instantiate once during application lifetime. Moreover, Angular service retains the data throughout the application’s life by using specific methods comprised of it.  Thus, Angular services share business, components, functions, and data with other components language and organizing an application. A controller directive can invoke the features of Angular service.  25. Explain NgRx.  A group of Angular libraries for reactive extensions is called NgRx. The redux pattern is implemented by NgRx/store by using the RxJS observables belonging to Angular 2. NgRx is useful in a variety of as it can simplify application state to plain objects. It implements a unidirectional flow of data. Many other libraries under NgRx are helpful in a variety of tasks.  26. What do you know about string interpolation in Angular? It is a special syntax that displays the component data using template extensions. It is also called mustache syntax.   27. Explain Angular authentication?  The Angular authentication process is as follows:  An authentication API receives user credentials and validates it. The authentication API is present on the server. Once the validation has been done, a JSON web token is reinstated containing information about the current user. JSON web token is then used to identify the user.   28. Explain Angular authorization.  The process or method restricting the access of users is called authorization. Once a user is logged in after authentication, he or she has a certain level of access. This level of access can be configured for different users. This is what we call Angular authorization.  29. What do you know about the scope hierarchy in Angular? The scope hierarchy is the organization of $scope objects into a skeleton by Angular. Views often utilize this hierarchy, and in this hierarchy, each view has its unique scope. This format has a parent scope that is capable of holding numerous child scopes. 30. What is the way to generate a class in Angular using Angular CLI? The following command can be utilized to create a class using CLI: ng generate class myClass [options] 31. Differentiate between Angular and jquery.  Jquery is a js based library whereas Angular, as we know, is a javascript framework for frontend development.  Angular does support two-way binding, but jquery does not.  Restful API can be consumed in Angular but not jquery has no support for Restful API.  Form validation is available in Angular but not in Jquery.  32. What is the difference between Angular and javascript expressions? The significant difference between Javascript and Angular expressions are as follows: We can write javascript expression under HTML tags, but we can do so with Angular expressions.  Filters are available in Angular but javascript has no provision for filters.  The angular expression can’t support loops, conditions and exceptions like javascript do.  33. Explain Data Binding? Data binding is the feature in Angular that allows establishing a connection between application data and DOM. This occurs between HTML and typescript or in other words between template and component.  34. In how many can data bunding be done? There are 3 ways to attain data binding, and they are as follows: Even binding Two-way binding Property binding 35. Elucidate Angular’s digest cycle.  Digest cycle in Angular is the strategy to monitor the watchlist to track alterations in the watch variable’s value. A comparison of later and present is done in every digest cycle.  36. How to trigger a digest cycle process manually? We can use the $apply() function to trigger the digest cycle process manually.  37. What is the use of Angular filters? When we need to format the value of the expression to display it to the user, we make use of Angular filters. These filters can be reinforced to directives, services, template or controllers. We could also create custom filters in Angular. The data is displayed only if a certain criterion is matched, and this is what filters can do by organizing data in such that way.  38. Name some Angular filters? The filters in Angular are as follows: json limitTo  currency  orderBy date  filter  lowercase number Thanks for reading and I hope it helps.
Angular 12 Crop Image Preview Before Upload using ngx-image-cropper
In this article, we will discuss the angular 10 crop image afore upload. This post will give you a simple example of an angular 11/10 cropper example. you'll learn image upload with crop in angular 10. This article goes into detail on angular 10 image upload with crop utilizing cropper. If you require to utilize image upload with a crop then you can facilely use the ngx-image-cropper npm package. it will provide you Cropping, Zooming, Scaling, and Preview functionality while uploading time. it's very facilely used with your angular 10 application. In this example, i will give you step by step explication of how you can image upload in a crop in angular 10 application. you can withal optically discern bellow screenshot for demo. Step 1: Create New App You can easily create your angular app using bellow command: ng new ngImageCrop Step 2: Install npm Packages In this step, we will install the ngx-image-cropper npm package for uploading the image crop function in angular. so let's run both commands: npm install ngx-image-cropper --save Step 3: Import ImageCropperModule Now, here we will import ImageCropperModule from ngx-image-cropper and then we add on declarations part. so let's update the app.module.ts file as like bellow: src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { ImageCropperModule } from 'ngx-image-cropper'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, ImageCropperModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Step 4: Update Component ts File Here, we will update app.component.ts file here, in this file we will write fileChangeEvent(), imageCropped(), imageLoaded(), cropperReady() and loadImageFailed() that provided by ngx-image-cropper. You can update as bellow app.component.ts file. src/app/app.component.ts import { Component } from '@angular/core'; import { ImageCroppedEvent } from 'ngx-image-cropper'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'ngImageCrop'; imageChangedEvent: any = ''; croppedImage: any = ''; fileChangeEvent(event: any): void { this.imageChangedEvent = event; } imageCropped(event: ImageCroppedEvent) { this.croppedImage = event.base64; } imageLoaded() { /* show cropper */ } cropperReady() { /* cropper ready */ } loadImageFailed() { /* show message */ } } Step 5: Update HTML File I used bootstrap class on this form. Here, we will update the HTML file as like below, so update it as like bellow: src/app/app.component.html <div class="container"> <div class="card"> <div class="card-header"> Anguler 11 Crop Image Example - HackTheStuff </div> <div class="card-body"> <input type="file" (change)="fileChangeEvent($event)" /> <div class="row" style="margin-top: 15px;"> <div class="text-center col-md-8"> <h5>Crop Image</h5> <image-cropper [imageChangedEvent]="imageChangedEvent" [maintainAspectRatio]="true" [aspectRatio]="4 / 4" [resizeToWidth]="256" format="png" (imageCropped)="imageCropped($event)" (imageLoaded)="imageLoaded()" (cropperReady)="cropperReady()" (loadImageFailed)="loadImageFailed()"></image-cropper> </div> <div class="text-center col-md-4"> <h5>Preview</h5> <img [src]="croppedImage" /> </div> </div> </div> </div> </div> i hope you like this article.
How to Create Multiple Layouts for Different pages in Angular 12
Angular is open-source web application framework written in Typescript. Angular is used for single page web application where a common layout uses for all HTML views. So all HTML views use common layout. In real life experience, a web application always have multiple common layouts. For example, Front user layouts, admin panel layout, login, register etc. These all views need different layouts than single common layouts. In this article, we will use different layout for login page while front side common views uses common layout. So lets start it. First of all create a fresh Angular project using ng new application command. AppRoutingModule You have probably added AppRoutingModule module in the project when creating Angular project. If you have not added AppRoutingModule module in the application, add routing module with below command: It will create app-routing.ts file in the src/app directory. ng generate module app-routing --flat --module=app index.html and app.component.ts Change in your main html files. index.html file is main file which serve root tag in it. We will use different layouts for all views. So remove the code and only keep the <app-root> tag. <base href="/"> <app-root></app-root> In app.component.html file, also remove default code and add add <router-outlet> tag. This tag will render the components html code according to url. <router-outlet></router-outlet> LoginComponent In this step, we will add login component and view in the project. So create login component using below ng command. ng generate component login This will add login folder with component and html file. Add login page HTML page in login/login.component.html file. <!doctype html> <html lang="en">   <head>     <title>Signin</title>      <link href="" rel="stylesheet">   </head>   <body class="text-center">     <main class="form-signin">       <form>         <h1 class="h3 mb-3 fw-normal">Signin</h1>         <div class="form-floating">           <input type="email" class="form-control" id="floatingInput" placeholder="">           <label for="floatingInput">Email</label>         </div>         <div class="form-floating">           <input type="password" class="form-control" id="floatingPassword" placeholder="Password">           <label for="floatingPassword">Password</label>         </div>         <div class="mb-3">         </div>         <button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>         <p class="mt-5 mb-3 text-muted">© 2021</p>       </form>     </main>   </body> </html> Add css code in login/login.component.css file. html, body {   height: 100%; } body {   display: flex;   align-items: center;   padding-top: 40px;   padding-bottom: 40px;   background-color: #f5f5f5; } .form-signin {   width: 100%;   max-width: 330px;   padding: 15px;   margin: auto; } .form-signin .checkbox {   font-weight: 400; } .form-signin .form-floating:focus-within {   z-index: 2; } .form-signin input[type="email"] {   margin-bottom: -1px;   border-bottom-right-radius: 0;   border-bottom-left-radius: 0; } .form-signin input[type="password"] {   margin-bottom: 10px;   border-top-left-radius: 0;   border-top-right-radius: 0; } .bd-placeholder-img {     font-size: 1.125rem;     text-anchor: middle;     -webkit-user-select: none;     -moz-user-select: none;     user-select: none; } @media (min-width: 768px) {     .bd-placeholder-img-lg {       font-size: 3.5rem;     } } Add new route for login in app-routing.module.ts file. All routes are added in routes constant which are exported to main module app.module.ts file. You will also need to import LoginComponent on the top of file. import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { LoginComponent } from './login/login.component'; const routes: Routes = [   // login route   { path: 'login', component: LoginComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } Now build and run the Angular application with command. It will open the application main link http://localhost:4200 in the default browser. ng serve --open Change link http://localhost:4200/login and you can see login HTML page rendered on the link. AppLayoutComponent In this step, we will create new component for common layout. We will create children routes for all common pages which will use this common layout. Run the following command which will create a AppLayoutComponent component. ng generate component app-layout Now add your common layout HTML code in app-layout/app-layout.component.html file. <router-outlet> tag in this file will render all children routes HTML code. <!doctype html> <html lang="en" class="h-100">   <head>     <meta charset="utf-8">     <meta name="viewport" content="width=device-width, initial-scale=1">     <meta name="description" content="">     <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">     <meta name="generator" content="Hugo 0.84.0">     <title>Dashboard</title>     <link href="" rel="stylesheet">   </head>   <body class="d-flex flex-column h-100">     <header>       <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">         <div class="container-fluid">           <a class="navbar-brand" routerLink="/" >Logo</a>           <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">             <span class="navbar-toggler-icon"></span>           </button>           <div class="collapse navbar-collapse" id="navbarCollapse">             <ul class="navbar-nav me-auto mb-2 mb-md-0">               <li class="nav-item">                 <a class="nav-link active" aria-current="page" routerLink="/">Home</a>               </li>               <li class="nav-item">                 <a class="nav-link active" aria-current="page" routerLink="/contact-us">Contact us</a>               </li>               <li class="nav-item">                 <a class="nav-link" routerLink="/login">Login</a>               </li>             </ul>           </div>         </div>       </nav>     </header>     <main class="flex-shrink-0">       <div class="container">         <router-outlet></router-outlet>       </div>     </main>     <footer class="footer mt-auto py-3 bg-light">       <div class="container">         <span class="text-muted">© 2021</span>       </div>     </footer>   </body> </html> You can add common CSS in app-layout/app-layout.component.css file. .bd-placeholder-img {   font-size: 1.125rem;   text-anchor: middle;   -webkit-user-select: none;   -moz-user-select: none;   user-select: none; } @media (min-width: 768px) {   .bd-placeholder-img-lg {     font-size: 3.5rem;   } } main > .container {   padding: 60px 15px 0; } Note that in Angular links are defined with routerLink attribute instead of href attribute. We have added three links in the navigation bar. We have already created login route. Now we will add two more routes and create component for it. So let's start by creating home component. HomeComponent and ContactUsComponent ng generate component home ng generate component contact-us In the home component, add HTML code in home/home.component.ts file. <h1 class="mt-5">Hello world</h1> <p class="lead">This is homepage layout</p> In the contact-us component, add contact us form in contact-us/contact-us.component.ts file. <h1 class="mt-5">Contact us page</h1> <p class="lead">Drop the message and we will contact you.</p> <div class="row g-5">   <div class="col-md-7 col-lg-8">     <h4 class="mb-3">Billing address</h4>     <form class="needs-validation" novalidate="">       <div class="row mb-3">         <div class="col-sm-6">           <label for="firstName" class="form-label">First name</label>           <input type="text" class="form-control" id="firstName" placeholder="" value="" required="">         </div>         <div class="col-sm-6">           <label for="lastName" class="form-label">Last name</label>           <input type="text" class="form-control" id="lastName" placeholder="" value="" required="">         </div>         <div class="col-12">           <label for="message" class="form-label">Your message</label>           <textarea class="form-control" id="message"></textarea>         </div>       </div>       <button class="btn btn-primary" type="submit">Submit</button>     </form>   </div> </div> Update app-routing.module.ts file by adding two new routes with children routes. import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { LoginComponent } from './login/login.component'; import { AppLayoutComponent } from './app-layout/app-layout.component'; import { HomeComponent } from './home/home.component'; import { ContactUsComponent } from './contact-us/contact-us.component'; const routes: Routes = [   // basic routes   {      path: '',     component: AppLayoutComponent,      children: [       { path: '', component: HomeComponent },       { path: 'contact-us', component: ContactUsComponent }     ]   },   // login route   { path: 'login', component: LoginComponent },   // redirect to home   { path: '**', redirectTo: '' } ]; @NgModule({   imports: [RouterModule.forRoot(routes)],   exports: [RouterModule] }) export class AppRoutingModule { } Now in your browser, go to project root url http://localhost:4200. You can see navigation bar with links. You can go through login or contact us page by this link. I hope this tutorial will help you.
How to Setup 404 Page in Angular 12
In this article, we will create 404 error page which will display when user access non-available route. We have started tutorial after fresh Angular Project. We create seperate component for 404 error page which will display incase user access non route link. To create a new component, run the following ng command. ng generate component page-not-found This command will create new component folder page-not-found in src/app folder. The folder includes page-not-found.component.ts, page-not-found.component.html and page-not-found.component.css file. In page-not-found.component.html file, input the the HTML code which you want to display in 404 error page. <!DOCTYPE html> <html> <head>     <meta charset="utf-8">     <title>Page not found</title> </head> <body>     <h1>Error 404</h1>     <p>The page you are looking for is not found.</p> </body> </html> If your page has css code, put it in page-not-found.component.css file. The css in this file will only apply to this component only. Now look at the page-not-found.component.ts file. This component has export class PageNotFoundComponent. Just before above, defined @Component decorator which provides metac data for the class. The selector property is the tag in parent component where the current component will load the HTML code.  The src/app/app.component.html file should have <router-outlet> tag where the current component will load its HTML template. So check the file should contain following tag. <router-outlet></router-outlet> The main html file located at src/index.html is main html file where Angular application loads in between <app-root></app-root> tag. So change the file with following one: <base href="/"> <app-root></app-root> Now Its time to setup routing. You generally have already have enabled routing when creating Angular application. Else you can create routing module with following command.  ng generate module app-routing --flat --module=app This will create app-routing.module.ts file in the src/app folder. Now in this file, import PageNotFoundComponent component at the top of the file and put two new routes at the end of routes array. import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { PageNotFoundComponent } from './hero-detail/hero-detail.component'; const routes: Routes = [   { path: '', component: HomeComponent },   { path: 'dashboard', component: DashboardComponent },   // all your other routes should come first   { path: 'page-not-found', component: PageNotFoundComponent },   { path: '**', component: PageNotFoundComponent }, ]; @NgModule({   imports: [RouterModule.forRoot(routes)],   exports: [RouterModule] }) export class AppRoutingModule { } We have uses wildcard route for 404 error page. We have to add these routes only at the end of routes array. Angular routing uses first-match route while checking wildcard in routes. Now run the following command in Terminal to start the application. ng serve --open This will open application in default browser. Now try to access /page-not-found or any non defined route, example http://localhost:4200/page-not-found. This will render 404 error page.
Two way Data Binding in Angular 12
When you create a variable or property to data, it is called as data binding in Angular. There are generally two types of binding. Property binding Event binding When you set values for property to HTML elements or directives, it is called property binding. Property bindind is used to work in HTML, like input value, dynamic CSS or Javascript, sharing data with components etc. To bind property in HTML element, Angular uses square brackets[] for property binding. Example: In your component, i.e. app.component.ts you define: imageUrl = '../assets/logo.png'; And you bind its value in HTML app.component.html as follow: <img [src]="imageUrl"> Event binding allows you to listen for events like click, mouse hover etc. It works same as Javascript events. In Angular, you define event name in () round brackets and its value is the method in component which will do task when the event occurs. Example: You define event in HTML view. app.component.html <button (click)="onSave()">Save</button> And in your component class, app.component.ts you set onSave() method which will listen click event on button. Now let's come to the main point, What is two-way binding? In a two-way binding, A component shares property data to HTML view and HTML event sends data to component. Two-way binding combines both property binding and event binding. Angular two-way binding syntax contains square brackets and round brackets[()]. Square bracket for property binding and round bracket for event binding. In this tutorial example, we will bind text box with property. When user changes textbox value, it will send data to comoponent and it will update HTML view. We will start from fresh new Angular application. You can install and setup new Angular project in this article[]. In the starting first add a username property in component class app.component.ts. import { Component } from '@angular/core'; @Component({   selector: 'app-root',   templateUrl: './app.component.html',   styleUrls: ['./app.component.css'] }) export class AppComponent {   username: string = 'Laravelcode'; } In your HTML view, add textbox which binds username property. On its value change, ngModel will update its value which ultimately change its value in h1 tag. <form action="#">   <h1>{{ username }}</h1>   <label for="name">Name:</label>   <input [(ngModel)]="username" id="username" name="username" placeholder="username"> </form> As we are using form elements, we need to import FormsModule in app.module.ts. Open AppModule class and update it as following: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; @NgModule({   declarations: [     AppComponent   ],   imports: [     BrowserModule,     AppRoutingModule,     FormsModule   ],   providers: [],   bootstrap: [AppComponent] }) export class AppModule { } If you want to give style to form, you can add CSS to app.component.css *, *:before, *:after {   -moz-box-sizing: border-box;   -webkit-box-sizing: border-box;   box-sizing: border-box;   color: #384047; } h1 {   margin: 0 0 30px 0;   text-align: center; } form {   max-width: 300px;   margin: 10px auto;   padding: 10px 20px;   background: #f4f7f8;   border-radius: 8px; } input {   background: rgba(255,255,255,0.1);   border: none;   font-size: 16px;   height: auto;   margin: 0;   outline: 0;   padding: 15px;   width: 100%;   background-color: #e8eeef;   color: #8a97a0;   box-shadow: 0 1px 0 rgba(0,0,0,0.03) inset;   margin-bottom: 30px; } label {   display: block;   margin-bottom: 8px; } Now run the Angular server with following command: ng serve --open It will open the form in default browser. Change the value in textbox. It will also reflect value in h1 <tag>. So this is how two-way binding works. We have implemented in as single component. In a next tutorial, we will see how we can share data between child component and parent component. I hope it will help you.
Share Data Between Child and Parent Components in Angular 12 Part 2
In the previous article, we have created parent component and set dynamic data view in modal. In this article, we will create child component and move modal view to it. So let's continue from creating a child component. Step 1: Create child component. You may have already running application in Terminal, so open new Terminal and run the following command in it. ng generate component child This will create new component folder. Now remove modal HTML code from parent view and move it to child view. Change property name from selectedUser to user. Here is child.component.ts file. <div class="modal fade" id="modal" tabindex="-1" aria-labelledby="modalLabel" aria-hidden="true">   <div class="modal-dialog">     <div class="modal-content">       <div class="modal-header">         <h5 class="modal-title" id="modalLabel">Modal title</h5>         <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>       </div>       <div class="modal-body">         <div *ngIf="user">           <p>{{ }}</p>           <p>{{ }}</p>         </div>       </div>       <div class="modal-footer">         <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>       </div>     </div>   </div> </div> Step 2: Parent view And in the parent.component.ts file, instead of modal, add the tag for child selector tag. Here is the file after changes. You will also need to pass the selectedUser property to child component. <table class="table table-hover">   <thead>     <tr>       <th scope="col">ID</th>       <th scope="col">Name</th>       <th scope="col">Email</th>       <th scope="col">Aciton</th>     </tr>   </thead>   <tbody>     <tr *ngFor="let user of users">       <td>{{ }}</td>       <td>{{ }}</td>       <td>{{ }}</td>       <td>         <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modal" (click)="onClick(user)">Show</button>       </td>     </tr>   </tbody> </table> <app-child [user]="selectedUser"></app-child> Step 3: @Input decorator in child component Now we are passing data from parent component to child component, so we need to add @Input decorator in ChildComponent class. Don't forget to import Input from angular/core module. import { Component, Input, OnInit } from '@angular/core'; @Component({   selector: 'app-child',   templateUrl: './child.component.html',   styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit {   @Input() user? : any;   constructor() { }   ngOnInit(): void {   } }   Step 4: Input fields in child view Now in the child view, we will put input field instead of text so we can change data that will push to parent component. In the child.component.html, add input fields instead of text. Here is the final view from child component. <div class="modal fade" id="modal" tabindex="-1" aria-labelledby="modalLabel" aria-hidden="true">   <div class="modal-dialog">     <div class="modal-content">       <div class="modal-header">         <h5 class="modal-title" id="modalLabel">Modal title</h5>         <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>       </div>       <div class="modal-body">         <div *ngIf="user">           <div class="mb-3 row">             <label for="name" class="col-sm-2 col-form-label">Name</label>             <div class="col-sm-10">               <input [(ngModel)]="" class="form-control" id="name">             </div>           </div>           <div class="mb-3 row">             <label for="email" class="col-sm-2 col-form-label">Email</label>             <div class="col-sm-10">               <input [(ngModel)]="" class="form-control" id="email">             </div>           </div>         </div>       </div>       <div class="modal-footer">         <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>       </div>     </div>   </div> </div> ngModel will bind two way, so when we change name or email to any user, it will also reflect into parent component also. Step 5: import FormsModule class We will two-way bind input fields, so add square brackets and round brackets to input fields. We have added form fields into the application so we also required to import FormsModule from angular/forms module in app.module.ts file. import { FormsModule } from '@angular/forms'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ParentComponent } from './parent/parent.component'; import { ChildComponent } from './child/child.component'; @NgModule({   declarations: [     AppComponent,     ParentComponent,     ChildComponent   ],   imports: [     BrowserModule,     AppRoutingModule,     FormsModule   ],   providers: [],   bootstrap: [AppComponent] }) export class AppModule { } Now everything is done. Open any user data and try to change name or email. This will also change data in table also.