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"