Getting Started with an Angular App in 2024

Sedang Trending 2 bulan yang lalu

Build amended Angular apps successful 2024

Lakindu Hewawasam

Bits and Pieces

If you’ve build accumulation apps pinch Angular, chances are that you’ve tally into capacity issues pinch nan Angular compiler. Let maine inquire you a elemental question:

Have you ever made a alteration successful your Angular app successful improvement and waited for a agelong clip for nan compilation to return place?

If you’re moving connected a mini project, you mightiness not look capacity issues for illustration this. But, I’ve worked connected an Angular task that uses hundreds of components, and moreover pinch Lazy Loading and Module Splitting, it causes slow load times successful accumulation and drastically effect personification experience.

So, thats wherever this article comes into nan picture. We’re going to locomotion done a modern attack to Angular improvement that focuses connected shifting distant from building elephantine monoliths, and attraction connected building composable Angular apps that are overmuch easier to maintain.

Pst, if you want to cheque retired nan code, here’s nan Bit Scope.

If you’re unfamiliar pinch Bit, it’s a build strategy that lets you design, develop, build, and type your components successful isolated environments.

It lets you build apps arsenic independent components wherever Bit keeps way of nan usages of nan components crossed your character and leverages its CI Server — Ripple CI, to propagate changes to nan constituent tree.

If you return a look astatine this sample constituent tree, you tin announcement that nan Typography constituent is being utilized crossed nan creation system. Additionally, location are much components that leverage different components, but successful different implementations.

So, successful a nutshell, we are making our components composable and pluggable successful immoderate nature. This is existent successful each front-end components.

Additionally, if you make a alteration to a constituent successful this tree, you’ll want to make judge that each nan components that dangle connected this azygous constituent get updated right?

For example, if I introduced a caller version successful nan Typography component, would you want your IconTextButton to cognize that a alteration was made automatically?

Bit leverages Ripple CI and understands nan changes successful nan character and will automatically update nan changes and guarantee nan components tally connected nan latest version!

Pretty cool, isn’t it?

Let’s get our hands soiled and deploy an Angular app utilizing Bit connected Netlify!

Step 01 — Pre-requisites

First, you’ll request to instal nan Bit CLI utilizing nan command:

npx @teambit/bvm install

Next, you’ll request to verify that nan CLI has been installed successfully by moving nan command:

bit --version

If you person installed Bit correctly, you should spot nan screenshot below.

Next, you will need an relationship connected Bit Cloud to big your composable app.

Step 02 — Creating an Angular Workspace

Next, you’ll person to create a Bit workspace to thief build composable Vue.js components we tin reuse crossed applications!

To do so, tally nan command:

bit caller hello-world-angular my-hello-world-angular --env teambit.community/starters/hello-world-angular --default-scope lakinduhewa.angular

Tip: Make judge to switch lakinduhewa.angular pinch your Bit Username and Scope.

If you’ve executed nan bid successfully, you should spot nan output:

Next, spell up and motorboat your dev server pinch nan command:

bit start

You should spot nan output connected localhost:3000:

You should spot 3 components generated for you:

  1. Hello World App: This is an Angular App Component. It is simply a instrumentality that lets you tally your components extracurricular of your Bit Server, and is simply a deployable unit.
  2. Angular Environment: This is simply a improvement situation that holds each nan dependencies, linting and build configurations that we will request erstwhile we build an independent Bit Component. Simply put, you don’t request an angular.json anymore. Everything is controlled by your environment.
  3. Hello World Component: This is simply a sample Bit creates for us.

Let’s cleanable nan workspace and get free of nan App and nan Dummy Component utilizing nan command:

bit region ui/hello-world && spot region hello-world-app

You should spot nan output below:

Step 03 — Creating a Sample Angular App pinch Bit

Let’s create a deployed app successful Angular. Let’s build a sample blog app that renders a database of articles. So, we’d request 3 things:

  1. A Deployable Angular app that serves nan article list.
  2. An entity that holds nan Article information shape
  3. A Node.js util usability that returns a database of blogs.

Building an Article Entity Component

Let’s first create an entity component. To do so, tally nan command:

bit create entity entities/article

If you tally into an error, make judge you adhd nan statement — "bitdev.node/node-env" to your teambit.generator/generator introduction successful your workspace.jsonc.

After moving nan command, you should spot nan output:

Afterward, unfastened up your article.ts and update it arsenic shown below:

export type PlainArticle = {
title: string;
description: string
}

export people Article {
backstage constructor(
/**
* title of nan article instance
*/
readonly title: string,

/**
* explanation of nan article
*/
readonly description: string
) { }

/**
* serialize a Article into
* a serializable object.
*/
toObject() {
return {
title: this.title,
description: this.description,
};
}

/**
* create a Article entity from a
* plain object.
*/
fixed from(plainArticle: PlainArticle) {
return caller Article(
plainArticle.title,
plainArticle.description
);
}
}

As you tin see, Bit offers highly maintainable entity component. You tin see validation logic for your entity wrong nan from usability wherever you tin propulsion errors if fields for illustration nan title is missing.

Apart from that, you tin specify portion tests for your entity. Open your article.spec.ts and see nan code:

import { Article } from './article.js';

const title = 'Sample Title';
const explanation = 'Sample Description';

it('has should create an article', () => {
const article = Article.from({ title, explanation });
expect(article.title).toBe(title);
expect(article.description).toBe(description);
});

As you tin see, we’ve written a portion trial to make judge nan Article entity is initialized pinch correct data. To confirm, let’s execute nan tests utilizing nan command:

bit test

Your tests should walk arsenic shown below:

Next, let’s vessel this disconnected to Bit Cloud utilizing nan commands:

bit tag && spot export

This will trigger a Ripple Build to build nan component:

Creating a Node.js Function To Fetch Articles

Next, let’s create a mock usability that returns a group of articles. To do so, let’s create a Node.js Function constituent utilizing nan command:

bit create module backend/get-articles

You should spot nan output:

Next, unfastened up get-articles.ts and update it arsenic follows:

import { Article } from "@lakinduhewa/angular.entities.article";

const articles: Article[] = [
Article.from({ description: 'Sample Description 01', title: 'Sample Title 01' }),
Article.from({ description: 'Sample Description 02', title: 'Sample Title 02' }),
Article.from({ description: 'Sample Description 03', title: 'Sample Title 03' }),
Article.from({ description: 'Sample Description 04', title: 'Sample Title 04' }),
Article.from({ description: 'Sample Description 05', title: 'Sample Title 05' }),
Article.from({ description: 'Sample Description 06', title: 'Sample Title 06' }),
]

/**
* returns a database of articles
*/
export usability getArticles(): Article[] {
return articles;
}

As you tin spot we’re utilizing nan Entity we created and we’re returning a database of mock articles. Let’s trial this by updating its trial file:

import { getArticles } from './get-articles.js';

it('fetches articles', () => {
expect(getArticles().length).toBeGreaterThan(0);
});

After moving nan tests, you should spot your module working:

Next, vessel it disconnected to Bit Cloud. You should spot your Ripple Build:

If you inspect your constituent tree, you tin spot nan following:

The Current Component Tree

You tin spot that nan Module we created depends connected nan Entity.

Creating an Article UI Component

Next, let’s create a elemental UI constituent that tin beryllium utilized to render an article. To do so, create an Angular constituent utilizing nan command:

bit create ng-standalone ui/article-card

This will create an Angular Component and will show nan output:

Open your article-card.component.ts and see nan code:

import { Component, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Article } from '@lakinduhewa/angular.entities.article';

@Component({
selector: 'article-card',
standalone: true,
imports: [CommonModule],
template: `
<div class="card">
<h2>{{ article.title }}</h2>
<p>{{ article.description }}</p>
</div>
`,
styleUrls: ['./article-card.component.scss']
})
export people ArticleCardComponent {
@Input() article!: Article;
constructor() { }
}

Next, update your CSS:

:host {
font-size: inherit;
}

.card {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
transition: 0.3s;
border-radius: 5px; /* 5px rounded corners */
padding: 16px;
margin: 16px 0;
background-color: white; /* Light taxable paper inheritance */
}

.card:hover {
box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2); /* Hover effect */
}

h2 {
margin-top: 0;
color: #333; /* Dark grey colour for nan title */
}

p {
color: #666; /* Lighter grey colour for nan explanation */
}

Afterward, you tin specify a elemental creation for your composition. This lets users spot really your constituent will look like. To do so, unfastened up your article-card.composition.ts and see nan following:

import { Component } from '@angular/core';
import { ArticleCardComponent } from './article-card.component';
import { Article, PlainArticle } from '@lakinduhewa/angular.entities.article';

@Component({
standalone: true,
selector: 'article-card-composition-cmp',
imports: [ArticleCardComponent],
template: `ArticleCard composition: <article-card
[article]="articleInstance"
/>`
})

export people ArticleCardCompositionComponent {
articleInstance: Article;

constructor() {
const plainArticle: PlainArticle = {
title: 'Example Title',
description: 'This is an illustration description.',
};
this.articleInstance = Article.from(plainArticle);
}
}

Afterward, you tin caput backmost to your Bit server and spot nan output:

Creating an Angular App

Now, each thats near is to create an Angular app. Create an app utilizing nan command:

bit create ng-app blog-app

This will motorboat a wizard:

Proceed by giving these configurations:

Finally, you should spot nan output:

Next, unfastened up your app.component.ts and let's usage nan ArticleCard and nan Mock Util we created:

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { getArticles } from '@lakinduhewa/angular.backend.get-articles';
import { ArticleCardComponent } from '@lakinduhewa/angular.ui.article-card';
import { Article } from '@lakinduhewa/angular.entities.article';

@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet, ArticleCardComponent],
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export people AppComponent {
articles: Article[]
title = 'blog-app';

constructor() {
this.articles = getArticles();
}
}

We’re initializing nan Articles successful nan App component. Next, unfastened up your app.component.html and let's render nan list:

<div>
<article-card *ngFor="let article of articles" [article]="article" />
</div>

<router-outlet />

We’re utilizing nan article paper and we’re iterating complete nan articles we initialized article utilizing nan ngFor directive. Next, let's motorboat nan app extracurricular nan Bit Server utilizing nan command:

bit tally blog-app

You should spot nan output below:

And that’s it! You build an Angular app pinch independent components. Go up and vessel this to Bit Cloud.

Finally, your tree should look for illustration this:

Step 04 — Deploying an Angular app

Let’s deploy nan app onto Netlify. Bit offers deployer components that we tin straight hook onto our component. Bit past uses it’s CI Server — Ripple CI to execute nan incremental updates to nan app to automatically deploy it to Netlify.

So, let’s instal nan deployer utilizing nan command:

bit instal @teambit/cloud-providers.deployers.netlify

Next, unfastened your plugin record — blog-app.bit-app.ts and configure nan deployer arsenic shown below:

import { NetlifyOptions, Netlify } from '@teambit/cloud-providers.deployers.netlify';

const netlify: NetlifyOptions = {
accessToken: "<<AUTH-TOKEN>>",
productionSiteName: 'my-awesome-site',
stagingSiteName: 'my-awesome-staging-site',
team: '<<YOUR-TEAM-NAME>>',
};

export const BlogAppOptions: AngularAppOptions = {
/**
* Name of nan app successful Bit CLI.
*/
name: 'blog-app',

/**
* Angular options for `bit build`
*/
angularBuildOptions: angularOptions,

/**
* Angular options for `bit run`
*/
angularServeOptions: angularOptions,

/**
* Env-specific options depending connected nan type of Angular used.
*/
ngEnvOptions,

/**
* Folder containing nan main record of your application
*/
sourceRoot: './src',

deploy: Netlify.deploy(netlify),
};

And that’s it! Now, each you person to do is export your App constituent onto Bit Cloud and Ripple CI will deploy your app.

You tin sojourn your Netlify console to spot nan app:

Pst, cheque retired nan app we worked connected here.

And that’s it! You nary longer person to beryllium chained to a gaint frontend monolith. Instead, you tin commencement building apps for illustration Lego done composable patterns and devices for illustration Bit.

If you want nan afloat code, cheque it retired connected my Bit Scope.

I dream you recovered this article helpful.

Thank you for reading.