Marcelle  Smith

Marcelle Smith

1595242560

Dynamically Loading Components with Angular CLI

This post and the code for it was a team effort, including my teammates Zack ReamRyan KaraBen Kindle, and Jason Lutz.

The code below was also inspired by the work of George Kalpakas, from PR#18428.

When moving from a multi-page application to a SPA, one of the problems that presents itself is the payload size upon initial load. By default, in an Angular application everything is bundled into one payload, which means as the application grows, so does the time that it takes to load.

The typical way to solve this problem is by utilizing the router to lazy load modules, as is shown in the Angular documentation. This is great when the content has a route, but what about situations where the components are not a part of a separate route?

In this post we will show how to leverage the Angular CLI to split components into their own bundles, which will allow them to only be loaded when needed.

Duping Angular CLI#

The Angular CLI, more specifically the @ngtools/webpack package, performs static analysis on an application during build time to locate all the lazy-loaded router paths. As each router path is analyzed Webpack creates a chunk that can then be loaded when route is activated. Contained within this chunk is the ModuleFactory for the given route.

Traditionally, being able to split without utilizing the router has been a difficult task, and is something that’s been requested. We can, however, take advantage of the static analysis and trick Angular CLI into splitting out our component modules, which enables us to dynamically load components.

Let’s dive in to how we can achieve this by creating a dynamic MessageComponent!

Creating our first Dynamic Component#

First, we create a folder called “dynamic-modules” to hold our components.

Within here, create another folder called “message”, to hold our MessageComponent. Next, add the following code:

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

@Component({
  selector: 'app-message',
  template: 'Hello World',
})
export class MessageComponent implements OnInit {
  constructor() { }

  ngOnInit() { }
}
<>

Now we need to create a module that declares this component. We will call this MessageModule.

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

import { DYNAMIC_COMPONENT } from '../../dynamic-component-loader/dynamic-component-manifest';
import { MessageComponent } from './message.component';

@NgModule({
  declarations: [
    MessageComponent,
  ],
  imports: [
  ],
  providers: [
  ],
  entryComponents: [
    MessageComponent,
  ],
})
export class MessageModule {}
<>

Note that, in order for a [ComponentFactory](https://angular.io/api/core/ComponentFactory) to be generated, the component must also be added to the module’s entryComponents.

#angular #angular-cli

What is GEEK

Buddha Community

Dynamically Loading Components with Angular CLI
Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Marcelle  Smith

Marcelle Smith

1595242560

Dynamically Loading Components with Angular CLI

This post and the code for it was a team effort, including my teammates Zack ReamRyan KaraBen Kindle, and Jason Lutz.

The code below was also inspired by the work of George Kalpakas, from PR#18428.

When moving from a multi-page application to a SPA, one of the problems that presents itself is the payload size upon initial load. By default, in an Angular application everything is bundled into one payload, which means as the application grows, so does the time that it takes to load.

The typical way to solve this problem is by utilizing the router to lazy load modules, as is shown in the Angular documentation. This is great when the content has a route, but what about situations where the components are not a part of a separate route?

In this post we will show how to leverage the Angular CLI to split components into their own bundles, which will allow them to only be loaded when needed.

Duping Angular CLI#

The Angular CLI, more specifically the @ngtools/webpack package, performs static analysis on an application during build time to locate all the lazy-loaded router paths. As each router path is analyzed Webpack creates a chunk that can then be loaded when route is activated. Contained within this chunk is the ModuleFactory for the given route.

Traditionally, being able to split without utilizing the router has been a difficult task, and is something that’s been requested. We can, however, take advantage of the static analysis and trick Angular CLI into splitting out our component modules, which enables us to dynamically load components.

Let’s dive in to how we can achieve this by creating a dynamic MessageComponent!

Creating our first Dynamic Component#

First, we create a folder called “dynamic-modules” to hold our components.

Within here, create another folder called “message”, to hold our MessageComponent. Next, add the following code:

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

@Component({
  selector: 'app-message',
  template: 'Hello World',
})
export class MessageComponent implements OnInit {
  constructor() { }

  ngOnInit() { }
}
<>

Now we need to create a module that declares this component. We will call this MessageModule.

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

import { DYNAMIC_COMPONENT } from '../../dynamic-component-loader/dynamic-component-manifest';
import { MessageComponent } from './message.component';

@NgModule({
  declarations: [
    MessageComponent,
  ],
  imports: [
  ],
  providers: [
  ],
  entryComponents: [
    MessageComponent,
  ],
})
export class MessageModule {}
<>

Note that, in order for a [ComponentFactory](https://angular.io/api/core/ComponentFactory) to be generated, the component must also be added to the module’s entryComponents.

#angular #angular-cli

Robert look

Robert look

1612755490

How To Create Angular Components in Angular 10/11 using CLI

will learn how to create angular components or Use ng generate component using CLI for creating angular components in your project.

we’ll learn the very easy command to generate code how to use the ng generate component command of Angular CLI, or its ng g c shortcut command, Learn this tutorial.

First of all, If you are new to these how-to, check out how to install and set up an angular project.

How To Create Angular Components In Angular 10/11 Using CLI

ng generate component about

original source: https://www.phpcodingstuff.com/blog/how-to-create-angular-components-in-angular-using-cli.html

#angular #component #cli

Autumn  Blick

Autumn Blick

1596732581

Agnostic components in Angular

When you’re building a reusable components library, API is very important. On one hand, you want a tidy, reliable solution, on the other — you need to take care of lots of specific use cases. Learn how to make components that work with everything and look like anything!

When you’re building a reusable components library, API is very important. On one hand, you want a tidy, reliable solution, on the other — you need to take care of lots of specific use cases. And it’s not just about working with diverse data. Your components must be flexible visually. Besides, it has to be easy to update and deliver across projects.

These components must be customizable like no other. And it shouldn’t be hard to do — they will be used by senior and junior developers alike. Also, since one of the reasons to make such a library is to reduce code duplication, configuration must not turn into a copy-paste exercise.

Data-agnostic components#

Say you’re making a drop-down menu button. What would be its API? Surely it would need an array of items for the menu. Probably, the first run would be an interface like the following:

interface MenuItem {
    readonly text: string;
    readonly onClick(): void;
}
<>

Fairly quickly, you’d add an option to disable an item. Then designers would come up with a menu with icons. Then they will draw them on the other side for the fellow project. The interface keeps growing, taking more and more cases into account. Great variety of flags turn your component into the United Nations assembly.

Looking familiar?

Generics to the rescue. If you build your component to not care about the data model at all — this problem seizes to exist. Instead of calling item.onClick it could emit clicked item. What to do with it is up to the library users. They are free to call item.onClick or organize their model differently.

In the case of disabled state, a component would use a handler. It’s a function that takes generic item as an argument and returns whether it is disabled or not. Handling different visual options would be explored later.


For a ComboBox, you could come up with an interface with string for display value and a property with the real value behind it. This seems reasonable. After all, when user types into ComboBox, options must be narrowed down by the string input.

interface ComboBoxItem {
    readonly text: string;
    readonly value: any;
}
<>

You would soon uncover limitations of this approach once design pops up where string is not enough. Besides, form contains a wrapper instead of the real value and filtering is not always limited to string representation. You could filter by phone number contacts that show names. And each new component like that brings new interface even if the underlying model is the same.

Here you can also use generics and provide a stringify handler to the component: (item: T) => string. A simple String(item) would work by default. This way, you can even use classes for options by defining toString method. As mentioned earlier, string is not always enough to filter. It’s another good case for handlers — we could pass a matching function to ComboBox. It would take user input and item as arguments and return true if item fits.

Another example where interface is often used — unique id. You might get your value in one request and options later in another. Then you will have a copy of the selected item in the array, not the same reference. Instead of an id property, you could have an identity matching function. It would take two items as arguments with the default value of simple triple _=_ comparison.

Many components, such as tabs, radio buttons, variety of lists don’t need to be aware of the data model they work with. Abstraction over it allows to create extendable code not tied to concrete realization. This means there will be no breaking changes with added features. Users will not have to adapt their data and components fit together like Lego blocks.

The same options component could go in context menu, SelectMultiSelect. Atomic components effortlessly make up bigger structures. However, generic data must be displayed somehow. Lists could have avatars, different colors, unread messages counters and so on.

Example drop-down with custom design

To make this work, we need to approach presentation in the same manner as we took on generic data.

#angular #angular-templates #angular-dynamic-components #typescript #api

Roberta  Ward

Roberta Ward

1595337024

Tutorial: Nx-style monorepo workspace with Angular CLI: Part 3

In Part 3 of this tutorial, we create the passenger info and flight search feature libraries. We use the generate project tool to create the mobile booking application and its test project. Finally, we create a mobile version of the flight search component template.

This tutorial is part of the Angular Architectural Patterns series.

In Part 2 of this tutorial, we used the generate project tool to generate the booking data access and shared data access workspace libraries with NgRx Store and Effects. We extracted a shared environments library and hooked everything up to the booking feature shell library.

In this part of the tutorial, we’re going to create the passenger info and flight search feature libraries, each with a routed component. After that, we’ll create the mobile booking application project and its end-to-end test project. Finally, we’ll use builder file replacement to create a mobile version of the flight search component template.

THIS AD MAKES CONTENT FREE. HIDE

Passenger info feature library#

Let’s create our first feature library, the passenger info feature which is part of the booking domain.

npm run generate-project -- library feature feature-passenger-info --scope=booking --npm-scope=nrwl-airlines
# or
yarn generate-project library feature feature-passenger-info --scope=booking --npm-scope=nrwl-airlines
<>

Generate passenger info feature library.

After generating the project using the previous commands and parameters, we get this file and folder structure.

libs/booking/feature-passenger-info
├── src
│   ├── lib
│   │   ├── passenger-info
│   │   │   ├── passenger-info.component.css
│   │   │   ├── passenger-info.component.html
│   │   │   ├── passenger-info.component.spec.ts
│   │   │   └── passenger-info.component.ts
│   │   ├── booking-feature-passenger-info.module.spec.ts
│   │   └── booking-feature-passenger-info.module.ts
│   ├── index.ts
│   └── test.ts
├── README.md
├── karma.conf.js
├── tsconfig.lib.json
├── tsconfig.spec.json
└── tslint.json
<>

The file and folder structure of the booking passenger info feature library.

This looks a little different from a feature shell library and a data access library.

After the generate project tool has created the workspace library with an entry point Angular module, it runs the commands in the next listing.

The generate project tool also removed the --no-common-module flag from the ng generate module command we saw earlier, since this Angular module will be declaring components.

ng generate component passenger-info --project=booking-feature-passenger-info --module=booking-feature-passenger-info.module.ts --display-block
<>

Generate component command run when generating a feature library.

Let’s look at the Angular module our tool has generated.

// booking-feature-passenger-info.module.ts
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';

import {
  PassengerInfoComponent,
} from './passenger-info/passenger-info.component';

@NgModule({
  declarations: [PassengerInfoComponent],
  imports: [
    CommonModule,
  ],
})
export class BookingFeaturePassengerInfoModule {}
<>

Initial entry point Angular module in the passenger info feature library.

The entry point Angular module shown in the previous listing is a good starting point. We need to set up the feature routing for our component though. This is done in the next listing.

// booking-feature-passenger-info.module.ts
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import {
  PassengerInfoComponent,
} from './passenger-info/passenger-info.component';

const routes: Routes = [
  {
    path: '',
    pathMatch: 'full',
    component: PassengerInfoComponent,
  },
];

@NgModule({
  declarations: [PassengerInfoComponent],
  imports: [
    RouterModule.forChild(routes),
    CommonModule,
  ],
})
export class BookingFeaturePassengerInfoModule {}
<>

Passenger info feature Angular module with route configuration for its entry point component.

Nice! Now we’ve prepared our feature library to be hooked up to the feature shell library’s routing configuration.

The generated component is what you’d expect. What it’d display in a real booking application is not really important for the purpose of this article.

Let’s hook up this feature to the booking application’s routing by adding a route configuration to the booking feature shell Angular module as seen here.

#angular #angular-cli #angular-workspace #monorepo #nx #series-angular-architectural-patterns