Saturday, 23 October 2021

Why OnChanges does not fire always

 

Template is Updated

Updating the DOM is part of Angular’s change detection mechanism The change detector checks each and every bound property for changes and updates the DOM if it finds any changes.

In the child component template, we have two bound properties. {{ message }} & {{ customer.name }}. Hence the change detector checks only these two properties and updates the DOM. The customer object also has code property. The change detector will never check it.

Why onChanges does not fire?

The Change detector also raises the OnChanges hook. But it uses a different techniques for comparison.

The change detector uses the === strict equality operator for detecting changes to the input properties. For primitive data types like string, the above comparison works perfectly

But in the case of an object like a customer, this fails. For Arrays/objects, the strict checking means that only the references are checked. Since the reference to the customer stays the same the Angular does not raise the OnChanges hook.

That leaves us two possible solutions

  1. Create a new customer and copy the old data to new customer
  2. We can Perform our own change detection using the ngDoCheck lifecycle hook

Update the updateCustomer method and create a new instance of customer every time

Sunday, 3 October 2021

How to Add Bootstrap to Angular

 What is Bootstrap

The bootstrap is a responsive mobile-first CSS framework for building Web Applications. It is open source and has all the features like Sass variables, mixins, responsive grid system, prebuilt components, and powerful JavaScript plugins.

Bootstrap consists of few CSS files & JS files.

The CSS files contains all the styles definitions.

Many of bootstrap components require the use of JavaScript to function. For Example, carousels, drop-down menus, auto-suggest, etc require bootstraps.js file. It also has depedency on jQueryPopper.js.

Install the bootstrap package

Instead of running from CDN, you can install the CSS Files locally. The correct way to do this is by installing the bootstrap package.

Run the following npm command to install bootstrap. This will install the latest version of the bootstrap

npm install --save bootstrap

Running the above command will copy the bootstrap files to the node_modules/bootstrap folder. But it will not include it in the app.

Open the angular.json file and locate the projects -> Bootstrap-example (our project name) -> architect -> build -> styles node.

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


Alternatively you can just add the @import directive to import it in the styles.css

@import "~../node_modules/bootstrap/dist/css/bootstrap.min.css"





Monday, 20 September 2021

Spring Cloud Config Server with Github

 1. Create a limit-service Client Spring Boot project from https://start.spring.io/


2. Create a spring-cloud-config-server Spring Boot project from https://start.spring.io/



3. Open application.properties in limits-service project and do two things;

spring.application.name=limits-service

server.port=8081


4. Open application.properties file in spring-cloud-config-server project.

spring.application.name=spring-cloud-config-server

server.port=8888


5. Open SpringCloudConfigServerApplication.java file in spring-cloud-config-server and include the below annotation there

@EnableConfigServer


6. Since Spring config server is starting at port 8888, we need to give the server address to limits-service. Add the below line in application.properties in limits-service project

spring.config.import=optional:configserver:http://localhost:8888


7. We can create a Local Git repo or Remote Git repo to add the properties files,

We need to give the path of properties files in application.properties of spring-cloud-config-server.


#Local Git config path

spring.cloud.config.server.git.uri=file:///D:/GitHub-Repo/git-localconfig-repo/


#Remote Git config path

spring.cloud.config.server.git.uri=https://github.com/amir35/git-config-repo


8. Remember the property file name should be same as that of microservice name.

Here microservice name is "limits-service". So properties name present at Git repo should be
"limits-service.properties"


9. Now you can start the limits-service server and you can see it will try to fetch data from spring-cloud-config-server which in turn will fetch data from limits-service.properties file from Git repo.


10. Now suppose you want to change any property from limits-service.properties file, you don't need to start server again for limits-service project.

Just you need to commit the files in Git repo and then execute one refresh endpoint.


11. Open application.properties file in limits-service and add below line:

management.endpoints.web.exposure.include=*

this will enable all the endpoints.

Then after making changes in the property file run this endpoint for changes to reflect on the microservice.

http://localhost:8081/actuator/refresh



Then execute the normal Rest endpoints as before and changes will reflect.


Source Code: Limits-service

Sunday, 12 September 2021

How to Configure GitHub repository with Eclipse Project

First time? I also spent most part of the day today trying to get my Spring Boot project in Eclipse connected to GitHub and I finally got it to work, so I thought I’d share my observations to make it easier for other new learners.


When we work on any project. We want to have it stored online on Github so that it is available to be taken into other places. To make your Local Eclipse project configured with Github, follow the below steps to Configure it.

Step 1: Click on New Button to create a New Repository


Step 2: Enter any Repository name and Click on the "Create repository" button.


Step 3: Copy the URL for the repository, say gitURL.



Step 4: Open Eclipse. Click on the Search icon on the right side and Type Git Repo. You will get the below option. Choose "Git Repositories" under the View section.



Step 5: Paste the gitURL here and Click on "Next".




Step 6: Your repository will start reflecting.



Step 7: Now Create a new Spring Boot(or any other) project.



Step 8: Give the name and other required information for the project.



Step 9: Right Click on Project. Then Select Team -> Share project.



Step 10: Select the Repository that you have created from the dropdown.





Step 11: Click on Finish.


Step 12: Go to Git Staging section. Add all the uncommitted files. Give the proper Commit message and then Click on Commit and Push.



Step 13: Click on Preview. The Github login box will appear.



Step 14: Given username and Token as password.



Step 15: Click on the Push-button.



Step 16: Now push is done. Go to the Github repository and the committed files will reflect there.




How to Configure GIT Token to push changes

 Follow the Below Steps to Configure GIT to push changes to the repository:


Step 1: Log in to your Github account

Step 2: Click on your image at the top right corner for Menu.

Step 3: Select the Setting



Step 4: Click on "Developer Settings"



Step 5: Click on "Personal Access Token" and then "Generate new Token"



Step 6: Give a name for Token and set the Expiration period. 



Step 7: Select all the access you wants to give and then click on the "Generate Token" button




Step 8: A new generated Token will be available. Copy that Token and keep it at someplace. You will not be able to see the token again on this page.

Step 9: After doing any change, click on "Commit and Push" under Git Staging.





Step 10: You will get Login box. Here give "User" as your Git username and "Password" as the Token generated.



Step 11: The changes will be pushed to the Git repository.



Saturday, 11 September 2021

How to Resolve “Failed to Configure a DataSource” Error

How to Resolve Failed to Configure a DataSource” Error:




Suppose we have a Spring Boot project, and we've added the spring-data-starter-jpa dependency and a MySQL JDBC driver to our pom.xml.

Cause:

Spring Boot auto-configuration tries to configure the beans automatically based on the dependencies added to the classpath.

And, since we have the JPA dependency on our classpath, Spring Boot tries to automatically configure a JPA DataSource. The problem is, we haven't given Spring the information it needs to perform the auto-configuration.

For example, we haven't defined any JDBC connection properties, and we'll need to do so when working with external databases like MySQL and MSSQL. On the other hand, we won't face this issue with in-memory databases like H2 since they can create a data source without all this information.

So, If we are not using JPA or JDBC and still we are having this issue. We can do following things to get rid of this error:

The class DataSourceAutoConfiguration is the base class for configuring a data source using the spring.datasource.* properties.

First, we can disable the auto-configuration using the spring.autoconfigure.exclude property in our application.properties file:

application.properties

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration


application.yaml

spring: autoconfigure: exclude: - org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration


Or, we can use the exclude attribute on our  @SpringBootApplication or @EnableAutoConfiguration annotation:

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})







Friday, 25 June 2021

Daily Activity Tracker in Angular

 Daily Activity Tracker


This Daily Activity Tracker Application is built in Angular.




Source Code: Angular Activity Tracker



Sunday, 20 June 2021

Wednesday, 16 June 2021

 Structural Directives in Angular


Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements.

There are three built-in structural directives, NgIfNgFor and NgSwitch.

NgFor:
 It is a repeater directive that customizes data display. It can be used to display a list of items.

NgIf:
 It removes or recreates a part of DOM tree depending on an expression evaluation.


Example:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  //title = 'StructuralDirective';

  title = "Welcome to Structural Directive Tutorials";

  showElement = true;

  color = "green";

  colors = ['red','green','orange'];

}

<h2>{{title}}</h2>

<!-- This will show only if showElement property is True in component class-->
<p *ngIf="showElement">This is ngIf directive</p>

<!--ngSwitch-->
<div [ngSwitch]="color">
  <div *ngSwitchCase="'red'">This is red</div>
  <div *ngSwitchCase="'green'">This is Green</div>
  <div *ngSwitchDefault>Invalid color</div>
</div>

<!--ngFor-->
<ul>
  <li *ngFor="let color of colors">{{color}}</li>
</ul>



Open the terminal window and enter the below command:



You will see the following on your Browser:












Wednesday, 2 June 2021

Bootstrapping in Angular: How It Works Internally

Bootstrapping in Angular


What is a Bootstrapping

Bootstrapping is a technique of initializing or loading our Angular application.

let’s walk through our code created in Create your First new Angular project and see what happens at each stage and how our AppComponent gets loaded and displays “app works!”. The Angular takes the following steps to load our first view.

  1. Index.html loads
  2. Angular, Third-party libraries & Application loads
  3. Main.ts the application entry point
  4. Root Module
  5. Root Component
  6. Template

Index.html Loads First

Web apps need a starting point. Index.html is usually the first page to load. Let us open the file and find out what it contains. You will find it under the src folder.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>GettingStarted</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>


There are no javascript files in the index.html. Neither you can see a stylesheet file. The body of the files has the following HTML tag.

<app-root></app-root>


How do Angular loads ?.  To Find out, let us build our application.

Building Application

To run our application, we use the Angular CLI command ng serve or NPM command npm start (npm start command actually translates into ng serve.)

ng serve does build our application but does not save the compiled application to the disk. It saves it in memory and starts the development server.

We use ng build to build our app. Open the command prompt and run the command. This will build and copy the output files to the dist folder.

ng build


Use ng build --prod to build and distribute the app for production. For testing/debugging use ng build. The production build optimizes, minimize and uglify the code.

Now open the dist and open the index.html.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>GettingStarted</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
 
  <script src="runtime-es2015.js" type="module"></script>
  <script src="runtime-es5.js" nomodule defer></script>
  <script src="polyfills-es5.js" nomodule defer></script>
  <script src="polyfills-es2015.js" type="module"></script>
  <script src="styles-es2015.js" type="module"></script>
  <script src="styles-es5.js" nomodule defer></script>
  <script src="vendor-es2015.js" type="module"></script>
  <script src="vendor-es5.js" nomodule defer></script>
  <script src="main-es2015.js" type="module"></script>
  <script src="main-es5.js" nomodule defer></script></body>
</html>


You can see that the compiler included five script files. They are runtimepolyfillsstylesvendor, & main. All these files have two versions one is es5 & the other one es2015.

runtime.js: Webpack runtime file
polyfills.js – Polyfill scripts for supporting the variety of the latest modern browsers
styles.js – This file contains the global style rules bundled as javascript file.
vendor.js – contains the scripts from the Angular core library and any other 3rd party library.
main.js – code of the application

These files are added by the Webpack module loader.

Full Article: Angular Bootstrapping Internal Working