= 🦴 Bare Bones Angular and Angular CLI Tutorial
:author: Matt Raible :email: matt@raibledesigns.com :revnumber: 17.0.0 :revdate: {docdate} :subject: Angular and Angular CLI :keywords: Angular, Angular CLI, TypeScript, JavaScript, Node, npm, Jasmine, Cypress :icons: font :lang: en :language: javadocript :sourcedir: . ifndef::env-github[] :icons: font endif::[] ifdef::env-github,env-browser[] :toc: preamble :toclevels: 2 endif::[] ifdef::env-github[] :status: :outfilesuffix: .adoc :!toc-title: :caution-caption: :fire: :important-caption: :exclamation: :note-caption: :paperclip: :tip-caption: :bulb: :warning-caption: :warning: endif::[] :toc: macro :source-highlighter: highlight.js
IMPORTANT: For a book of this tutorial, please check out https://www.infoq.com/minibooks/angular-mini-book/[The Angular Mini-Book]. Its "Build an Angular App" chapter was inspired by this tutorial.
This tutorial shows you how to build a bare-bones search and edit application using https://angular.io[Angular] and https://github.com/angular/angular-cli[Angular CLI] version 17.
toc::[]
ifdef::env-github[] TIP: It appears you're reading this document on GitHub. If you want a prettier view, install https://chrome.google.com/webstore/detail/asciidoctorjs-live-previe/iaalpfgpbocpdfblpnhhgllgbdbchmia[Asciidoctor.js Live Preview for Chrome], then view the https://raw.githubusercontent.com/mraible/ng-demo/main/README.adoc?toc=left[raw document]. Another option is to use the https://gist.asciidoctor.org/?github-mraible%2Fng-demo%2Fmain%2F%2FREADME.adoc[DocGist view]. endif::[]
.Source Code
If you'd like to get right to it, the https://github.com/mraible/ng-demo[source is on GitHub]. To run the app, use ng serve. To test it, run ng test. To run its integration tests, run ng e2e.
Check out the bonus section at the end of this document for Angular Material, Bootstrap, Auth0, and Electron tutorials.
toc::[]
== What you'll build
You'll build a simple web application with Angular CLI, a tool for Angular development. You'll create an application with search and edit features.
== What you'll need
If you don't have Angular CLI installed, install it:
NOTE: IntelliJ IDEA Ultimate Edition has the best support for TypeScript. If you'd rather not pay for your IDE, checkout https://code.visualstudio.com/[Visual Studio Code].
== Create a new Angular project
Create a new project using the ng new command:
When prompted for the stylesheet format, choose "CSS" (the default). Accept the default (No) for SSR (Server-Side Rendering) and SSG (Static Site Generation).
This will create a ng-demo project and run npm install in it. It takes about a minute to complete, but will vary based on your internet connection speed.
You can see the version of Angular CLI you're using with the ng version command.
$ ng version
Angular CLI: 17.0.5 Node: 18.18.2 Package Manager: npm 9.8.1 OS: darwin arm64
Angular: ...
If you run this command from the ng-demo directory, you'll see even more information.
...
Angular: 17.0.5 ... animations, cli, common, compiler, compiler-cli, core, forms ... platform-browser, platform-browser-dynamic, router
== Run the application
The project is configured with a simple web server for development. To start it, run:
You should see a screen like the one below at http://localhost:4200.
[[default-homepage]] .Default homepage image::src/assets/images/default-homepage.png[Default Homepage, 800, scaledwidth="100%"]
You can make sure your new project's tests pass, run ng test:
== Add a search feature
To add a search feature, open the project in an IDE or your favorite text editor.
=== The Basics
In a terminal window, cd into the ng-demo directory and run the following command to create a search component.
Open src/app/search/search.component.html and replace its default HTML with the following:
Add a query property to src/app/search/search.component.ts. While you're there, add a searchResults property and an empty search() method.
export class SearchComponent implements OnInit { query: string | undefined; searchResults: any;
constructor() { }
ngOnInit(): void { }
search(): void { }
In src/app/app.routes.ts, modify the routes constant to add SearchComponent as the default:
import { Routes } from '@angular/router'; import { SearchComponent } from './search/search.component';
Run ng serve again you will see a compilation error.
To solve this, open search.component.ts. Import FormsModule and JsonPipe:
import { Component, OnInit } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { JsonPipe } from '@angular/common';
Now you should be able to see the search form.
[[search-component]] .Search component image::src/assets/images/search-without-css.png[Search component, 800, scaledwidth="100%"]
If yours looks different, it's because I trimmed my app.component.html to the bare minimum.
If you want to add styling for this component, open src/app/search/search.component.css and add some CSS. For example:
IMPORTANT: The :host allows you to target the container of the component. It's the only way to target the host element. You can't reach the host element from inside the component with other selectors because it's not part of the component's own template.
This section has shown you how to generate a new component and add it to a basic Angular application with Angular CLI. The next section shows you how to create and use a JSON file and localStorage to create a fake API.
=== The Backend
To get search results, create a SearchService that makes HTTP requests to a JSON file. Start by generating a new service.
Create src/assets/data/people.json to hold your data.
Modify src/app/shared/search/search.service.ts and provide HttpClient as a dependency in its constructor.
In this same file, create a getAll() method to gather all the people. Also, define the Address and Person classes that JSON will be marshalled to.
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' }) export class SearchService {
constructor(private http: HttpClient) { }
getAll(): Observable<Person[]> { return this.http.get<Person[]>('assets/data/people.json'); } }
export class Address { street: string; city: string; state: string; zip: string;
constructor(obj?: any) { this.street = obj?.street || null; this.city = obj?.city || null; this.state = obj?.state || null; this.zip = obj?.zip || null; } }
export class Person { id: number; name: string; phone: string; address: Address;
To make these classes easier to consume by your components, create src/app/shared/index.ts and add the following:
The reason for creating this file is so you can import multiple classes on a single line rather than having to import each individual class on separate lines.
In search.component.ts, add imports for these classes.
You can now add a proper type to the searchResults variable. While you're there, modify the constructor to inject the SearchService.
export class SearchComponent implements OnInit { query: string | undefined; searchResults: Person[] = [];
Then update the search() method to call the service's getAll() method.
At this point, if your app is running, you'll see the following message in your browser's console.
To fix the "No provider" error from above, update app.config.ts to import and use provideHttpClient.
import { provideHttpClient } from '@angular/common/http';
Now clicking the search button should work. To make the results look better, remove the <pre> tag and replace it with the following in search.component.html.
@if (searchResults.length) {
<table> <thead> <tr> <th>Name</th> <th>Phone</th> <th>Address</th> </tr> </thead> <tbody> @for (person of searchResults; track person; let i = $index) { <tr> <td>{{person.name}}</td> <td>{{person.phone}}</td> <td>{{person.address.street}}<br/> {{person.address.city}}, {{person.address.state}} {{person.address.zip}} </td> </tr> } </tbody> </table> } ----Then add some additional CSS to search.component.css to improve its table layout.
table { margin-top: 10px; border-collapse: collapse; }
th { text-align: left; border-bottom: 2px solid #ddd; padding: 8px; }
Now the search results look better.
[[search-results]] .Search results image::src/assets/images/search-results.png[Search Results, 800, scaledwidth="100%"]
But wait, you still don't have search functionality! To add a search feature, add a search() method to SearchService.
import { map, Observable } from 'rxjs'; ...
Then refactor SearchComponent to call this method with its query variable.
This won't compile right away.
[ERROR] TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'. [plugin angular-compiler]
Since query will always be assigned (even if it's empty), change its variable declaration to:
This is called a https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#definite-assignment-assertions[definite assignment assertion]. It's a way to tell TypeScript "I know what I'm doing, the variable will be assigned."
Now search results will be filtered by the query value you type in.
This section showed you how to fetch and display search results. The next section builds on this and shows how to edit and save a record.
== Add an edit feature
Modify search.component.html to wrap the person's name with a link.
Add RouterLink as an import to search.component.ts so everything will compile:
import { RouterLink } from '@angular/router';
Run the following command to generate an EditComponent.
Add a route for this component in app.routes.ts:
import { EditComponent } from './edit/edit.component';
Update src/app/edit/edit.component.html to display an editable form. You might notice I've added id attributes to most elements. This is to make it easier to locate elements when writing integration tests.
@if (person) {
<h3>{{person.name}}</h3> <div> <label>Id:</label> {{person.id}} </div> <div> <label>Name:</label> <input [(ngModel)]="person.name" name="name" id="name"

AI赋能电商视觉革命,一站式智能商拍平台
潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使 用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。


企业专属的AI法律顾问
iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。


稳定高效的流量提升解决方案,助力品牌曝光
稳定高效的流量提升解决方案,助力品牌曝光


最新版Sora2模型免费使用,一键生成无水印视频
最新版Sora2模型免费使用,一键生成无水印视频


实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。


选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。


AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。


最强AI数据分析助手
小浣熊家族Raccoon,您的AI智能助手,致力于通过先进的人工智能技术,为用户提供高效、便捷的智能服务。无论是日常咨询还是专业问题解答,小浣熊都能以快速、准确的响应满足您的需求,让您的生活更加智能便捷。


像人一样思考的AI智能体
imini 是一款超级AI智能体,能根据人类指令,自主思考、自主完成、并且交付结果的AI智能体。


AI数字人视频创作平台
Keevx 一款开箱即用的AI数字人视频创作平台,广泛适用于电商广告、企业培训与社媒宣传,让全球企业与个人创作者无需拍摄剪辑,就能快速生成多语言、高质量的专业视频。
最新AI工具、AI资讯
独家AI资源、AI项目落地

微信扫一扫关注公众号