Angular Question and Answers

Custom sorting using Material

https://technology.amis.nl/frontend/sorting-an-angular-material-table/


difference between ng build and ng build -- prod

ng build --stats-json 
ng build --prod --stats-json 

Angular Stats - ng build Vs ng build --prod

ng build ng build --prod
 environment.ts - will be used environment.prod.ts
 source map will be generated source map will not generate
 No Uglification Uglification
 No Tree shaking Tree shaking
 No AOT AOT Enabled
 No Bundling Bundling


Angular AOT vs JIT
1. JIT and AOT in Angular are: Just-in-Time (JIT), compiles your app in the browser at runtime. Ahead-of-Time (AOT), compiles your app at build time on the server.

2. The compiler works in JIT mode (Just-in-Time), which means it runs on the user machine every time the app is loaded. Every time you run an Angular app, the JIT compiler generates JavaScript for each component to render the app.

3. The compiler runs during build time and performs the compilation of the templates so the app can be rendered instantly at run time, significantly improving performance. It will inline all HTML and CSS for components into the JavaScript to avoid requesting these files separately, thus reducing the number of external Ajax requests.

how to improve initial load time/performance of angular app?
1. AOT build.
2. “Check your bundle sizes”
3. Lazy loading
4. Updating Angular and angular-cli
5. RxJS 6
6. Optimizing load of static content
7. Compressing images and removing unused fonts.
8. remove unnecessary js and css ink from index.html
9. source-map=false: remove source map will also reduce bundle size
    Try disabling source maps by running ng serve --sourcemap=false
10. don’t import @animation packages into the application to reduce bundle size and it gives the performance improvement.
11. Preserve White space: To remove unnecessary new lines, tabs and white spaces we can add below code(decrease bundle size)
// in component decorator you can now add:
“preserveWhitespaces: false”
// or in tsconfig.json:
“angularCompilerOptions”: { “preserveWhitespaces”: false}`

To improve runtime performance: 

1. Learn about how change detection works in angular to Detach Change Detector from some components
2. use trackBy in *ngFor  (If the object reference is broken by updating the content of the object, Angular removes the related DOM node completely and recreate it again even though the actual change required is for only a small part of the DOM node. This issue can be easily solved by using trackBy.)

3.Unsubscribing Observables (To avoid memory leaks)
4. Less global Variables
5 instead of classes for pojo create interface


6. If loading a module while navigating takes too much time, you could consider eagerly preloading modules instead. What this does is load your main application module first and display your view, and in the background load all the other modules even before you navigate to them.
You can use the following RouterModule configuration to make that work:
RouterModule.forRoot(appRoutes, {
    preloadingStrategy: PreloadAllModules
})
7

how-to-detect-refresh-page-and-redirect-to-another-page in angular
Add the below code in your app.component.ts file

@HostListener('window:beforeunload') goToPage() {
    this.router.navigate(['/hello']);
  }

https://stackblitz.com/edit/angular-how-to-detect-refresh-page-and-redirect-to-another-page?file=src%2Fapp%2Fapp.component.ts

Difference between BrowserModule vs CommonModule vs ApplicationModuel in angular?
1. BrowserModule provides services that are essential  launch and run a browser app.
   BrowserModule also re-exports CommonModule from @angular/common and ApplicationModule from @angular/core,which means that  components in the AppModule module also have access to the Angular directives every       app needs, such as NgIf and NgFor.
   2. CommonModule (all the basics of Angular templating: bindings, *ngIf, *ngFor…), except in the first app module, because it’s already part of the BrowserModule.

   3. ApplicationModule - it Configures the root injector for an app with providers of @angular/core dependencies that ApplicationRef needs to bootstrap components.


  3. What you have to understand is, with Angular, you create modular application and there are two types of modules. One is root module and another is feature module.
  • Root module imports the BrowserModule (if you are rendering in browser). This has the same stuffs as CommonModule but also stuffs that are used for rendering.
  • Now if you are creating a feature module, since you already have BrowserModule imported in your root module, it does not make sense and it's an overhead to import the Browser module in your feature module. Also, importing CommonModule  frees feature modules for use on any target platform (e.g. native mobile latform), ot just browsers. That's why you import CommonModule in your feature modules and BrowserModule in your root module.

What is feature module in Angular?
1. we want our feature modules to be platform independent. That's why we only import the CommonModule there, which only exports common directives and pipes.

2. When it comes to components, pipes and directives, every module should import its own dependencies disregarding if the same dependencies were imported in the root module or in any other feature module. In short, even when having multiple feature modules, each one of them needs to import the CommonModule.

3. We are using a new property called exports. Every element defined in the declarations array is private by default. We should only export whatever the other modules in our application need to perform its job. In our case, we only need to make the CreditCardComponent visible because it's being used in the template of the AppComponent.

4. Here's the tricky part of Angular modules. While components,  pipes and directives are scoped to its modules unless explicitly exported, services are globally available unless the module is lazy loaded.


how to load custom module If I don't want to use loadChilderen()
if you organized your modules this way, you can still use the loadChildren keyword without actually Lazy Loading the module, as a proof that your module is independent and well-structured:





This way there’s no need for the parent module to import your child module’s components to put them in the routing configuration: from localhost/contacts/ on, the ContactsModule will be responsible for its routes.

Another benefit from using the Lazy approach is that we can also lazy load all the modules and preload them as soon as the app starts:




Even better, we can define our custom strategy for preloading modules! We just need to set an attribute on the routes we want to preload, and write a new class to be used as our preloadingStrategy: this class will check for the routes’ attributes and if it finds them, the router will preload those routes!




Where should I put all my global services?
AppModule. This is because services are app-scoped, which means that they can be accessed from every module.

This means that if we provide a service in a child module, that service is still available in the parent module! How’s that even possible? That’s because they share the same injector! 
What I just said is true, but not if those children modules are lazy loaded: every lazy module has its own injector! What that means is that a service provided in a lazy module is only accessible in that module. But it can still access the services previously provided by non-lazy modules (such as AppModule)!

will all child module have it's own Injector?
yes
what if UserProfileModule gets imported more than 2 times? Can we prevent it?
if UserProfileModule gets imported more than 2 times then there will be 2 child injector and services/components/directives/pipes will have 2 different objects. so we should not allow loading/importing our UserProfileModule more than once.
We can use a little trick to do that: inside our CoreModule, we can… inject CoreModule! If Angular injects it correctly, it means that a CoreModule has been already created, and we can throw an error:




This is particulary useful if you’re in a team with some unexperienced devs and you want to make sure nothing strange happens 😃 You can use the same approach to make sure your singleton services are singletons, just inject them into themselves and if they are injected, throw an error!


How to change import of services using tsconfig.json?
 importing the single services from Core/SharedModule could be messy. Imagine that one of your View Modules is located some layers deep in the folder structure; in order to import and use a global service you’d have to write something like this:
import { AuthService } from ‘../../../../core/services/auth.service’;
That’s awful! And what if the folder structure changes?
What we can do, very easily, is to add a few lines to our tsconfig.json file, this way:




Also, we’d like to import our services from ‘@app/core’, not from ‘@app/core/services/auth.service’, which is tedious. For that, in our CoreModule folder, use can create an index.ts file and re-export all of our services: now we can import directly from ‘@app/core’!






What is closure function?

https://www.w3schools.com/js/js_function_closures.asp

What is difference var, let and const?
Variables created without a declaration keyword (varlet, or const) are always global, even if they are created inside a function.


What's the difference between platform-browser and platform-browser-dynamic?

"Platform-browser" Package is used to control some of the following browser things.

  1. We can change the title of the page dynamically.
  2. Its used to set,get,update browser meta data's
  3. Also we can disable or enable browser debugging tool with the help of functions available in this package
  4. It contains code shared for browser execution (DOM thread, WebWorker)
  5. Ahead-of-Time pre-compiled version of application being sent to the browser. Which usually means a significantly smaller package being sent to the browser.
platform-browser-dynamic is a function used to bootstrap an Angular application.
  1. It contains the client side code that processes templates (bindings, components, ...) and reflective dependency injection.
  2. Uses Just-in-Time compiler and make's application compile on client-side.
  3. When the offline template compiler is used, platform-browser-dynamic isn't necessary because all reflective access and metadata are converted to generated code.
Difference between ngmodule-providers /  component-providers / component-view providers

https://codecraft.tv/courses/angular/dependency-injection-and-providers/ngmodule-providers-vs-component-providers-vs-component-viewproviders/


How to update existing angular CLI

After reading some issues reported on the GitHub repository, I found the solution.

In order to update the angular-cli package installed globally in your system, you need to run:

npm uninstall -g @angular/cli
npm install -g @angular/cli@latest

Depending on your system, you may need to prefix the above commands with sudo.

Also, most likely you want to also update your local project version, because inside your project directory it will be selected with higher priority than the global one:

rm -rf node_modules
npm uninstall --save-dev @angular/cli
npm install --save-dev @angular/cli@latest
npm install

How to generate new component in the existing folder.
ng g c mybiodata/reg --flat

How to restrict size of angular bundled?
In Angular 7, there is bundle budget added in angular.json as shown below: 

"budgets": [
                {
                  "type""initial",
                  "maximumWarning""2mb",
                  "maximumError""5mb"
                },
                {
                  "type""anyComponentStyle",
                  "maximumWarning""6kb",
                  "maximumError""10kb"
                }
              ]

Budgets is a feature added to Angular CLI which allows you to set limit inside your configuration to make sure your application size is within the limit set. You can set the size so that the app can be warned when the limit is crossed.

explain tsconfig.json and tslint.json and polyfill.ts and  tsconfig.spec.json and  typings.d.ts?

tsconfig.json: This basically contains the compiler options required during compilation.

tslint.json: This is the config file with rules to be considered while compiling. The src/ folder is the main folder, which internally has a different file structure.

polyfill.ts This is mainly used for backward compatibility

tsconfig.spec.json This helps maintain the details for testing. 

typings.d.ts It is used to manage the Typescript definition.


Difference between Structural and attribute directives.

Structural directive.Attribute directive.
Structural directives are responsible for HTML layout. They shape and modify the DOM's structure by adding, removing, or manipulating elements. .Attribute directive are used as element attributes that change the appearance or behavior of an element, component, or another directive. .
You can only apply one structural directive to a host element.You can apply many attribute directives to one host element.
*ngIf and *ngFor are examples.ngStyle and ngClass are builtin attribute directives.

How to send-data-through-routing-paths-in-angular

https://stackoverflow.com/questions/44864303/send-data-through-routing-paths-in-angular

how-to-use-trackby-in-angular-with-example
    https://codebriefly.com/how-to-use-trackby-in-angular-with-example/

https://medium.com/@michelestieven/organizing-angular-applications-f0510761d65a




SHARE

esant technology

0 comments :

Post a Comment