search
HomeWeb Front-endJS TutorialCreating a Basic Framework for Angular 18

Создание базовой структуры для Angular 18

Previously, we looked at creating and setting up a new Angular project. In this article we will analyze the basic structure.

Let me remind you that the series is devoted to the development of a web application for searching for airline tickets and hotels. The project is based on a project from Alfa Travel - travel.alfabank.ru

The site consists of the following blocks:

  • Two screens: mobile and browser versions;
  • 4 main pages in which the block with the form changes;
  • Technical section;
  • Search for tickets and hotels;
  • Show http errors - 404, 403 and 500.

This allows us to highlight the main parts:

  • Basic layout containing header, content and footer;
  • The only main one that would display the required form;
  • Search results.

Setting up AppComponent

Change the AppComponent so that it only outputs routerOutlet.

import { ChangeDetectionStrategy, Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';

@Component({
  selector: 'baf-root',
  standalone: true,
  imports: [RouterOutlet],
  template: '<router-outlet></router-outlet>',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {}

Delete unused files: app.component.spec.ts, app.component.scss and app.component.html.

Add configuration for the browser version in app.config.browser.ts:

import { ApplicationConfig, mergeApplicationConfig } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';

import { appConfig } from './app.config';

const browserConfig: ApplicationConfig = {
  providers: [provideAnimations()],
};

export const config = mergeApplicationConfig(appConfig, browserConfig);

And import it into main.ts:

import { bootstrapApplication } from '@angular/platform-browser';

import { AppComponent } from './app/app.component';
import { config } from './app/app.config.browser';

bootstrapApplication(AppComponent, config).catch((err) => console.error(err));

Adding hammerjs

For the mobile version we need to work with touches and swipes, so we use hammerjs

Install the dependency:

yarn add -D hammerjs @types/hammerjs

Connect animation and hammerjs in the browser:

import 'hammerjs';

import { ApplicationConfig, mergeApplicationConfig } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';

import { appConfig } from './app.config';

const browserConfig: ApplicationConfig = {
  providers: [provideAnimations()],
};

export const config = mergeApplicationConfig(appConfig, browserConfig);

You need to set the configuration for hammerjs.

Create a new core folder, in which we will store everything that is an integral part of the project.

mkdir src/app/core
mkdir src/app/core/lib
echo >src/app/core/index.ts
mkdir src/app/core/lib/hammer
echo >src/app/core/lib/hammer/hammer.ts

In hammer.ts we specify the config:

import { EnvironmentProviders, importProvidersFrom, Injectable, Provider } from '@angular/core';
import { HAMMER_GESTURE_CONFIG, HammerGestureConfig, HammerModule } from '@angular/platform-browser';

@Injectable()
export class HammerConfig extends HammerGestureConfig {
  override overrides = {
    swipe: { velocity: 0.4, threshold: 20 },
    pinch: { enable: false },
    rotate: { enable: false },
  };
}

export function provideHammer(): (Provider | EnvironmentProviders)[] {
  return [
    importProvidersFrom(HammerModule),
    {
      provide: HAMMER_GESTURE_CONFIG,
      useClass: HammerConfig,
    },
  ];
}

Export to src/app/core/index.ts:

export * from './lib/hammer/hammer';

For quick access, add an alias to tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "strict": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "sourceMap": true,
    "declaration": false,
    "experimentalDecorators": true,
    "moduleResolution": "bundler",
    "importHelpers": true,
    "target": "ES2022",
    "module": "ES2022",
    "useDefineForClassFields": false,
    "lib": ["ES2022", "dom"],
    "baseUrl": ".",
    "paths": {
      "@baf/core": ["src/app/core/index.ts"]
    }
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}

Note that you also need to specify the baseUrl.

Connect in the browser version:

import { ApplicationConfig, mergeApplicationConfig } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';

import { provideHammer } from '@baf/core';

import { appConfig } from './app.config';

const browserConfig: ApplicationConfig = {
  providers: [provideAnimations(), provideHammer()],
};

export const config = mergeApplicationConfig(appConfig, browserConfig);

Creating a Layout

The layout is common to the entire web application. Let's add a new UI folder in which we will store the components.

mkdir src/app/ui
mkdir src/app/ui/layout/lib
echo >src/app/ui/layout/index.ts

Run the command:

yarn ng g c layout

Move the content to src/app/ui/layout/lib.

We see that everything is created without the attributes we need and with test files:

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

@Component({
  selector: 'baf-layout',
  standalone: true,
  imports: [],
  templateUrl: './layout.component.html',
  styleUrl: './layout.component.scss'
})
export class LayoutComponent {}

In angular.json we will specify the properties:

{
  "@schematics/angular:component": {
    "style": "scss",
    "changeDetection": "OnPush",
    "skipTests": true
   }
}

Edit LayoutComponent:

import { ChangeDetectionStrategy, Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';

@Component({
  selector: 'baf-results',
  standalone: true,
  imports: [RouterOutlet],
  templateUrl: './layout.component.html',
  styleUrl: './layout.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class LayoutComponent {}

Add a header, content and footer:

<router-outlet name="top"></router-outlet>
<header>
  <router-outlet name="header"></router-outlet>
</header>
<main>
  <router-outlet name="main-top"></router-outlet>
  <router-outlet></router-outlet>
  <router-outlet name="main-bottom"></router-outlet>
</main>
<footer>
  <router-outlet name="footer"></router-outlet>
</footer>
<router-outlet name="bottom"></router-outlet>

A few styles:

:host {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}

header,
footer {
  flex-shrink: 0;
}

main {
  flex-grow: 1;
  overflow-x: hidden;
}

Export the component to src/app/ui/layout/index.ts:

export * from './lib/layout.component';

And write the alias in tsconfig.json:

{
  "paths": {
     "@baf/core": ["src/app/core/index.ts"],
     "@baf/ui/layout": ["src/app/ui/layout/index.ts"]
  }
}

Reset styles

Before displaying the layout, you need to configure the styles in the application.

To reset the default appearance in the browser, just the following:

/* You can add global styles to this file, and also import other style files */
@use '@angular/cdk' as cdk;

// Hack for global CDK dialogs styles
@include cdk.overlay();

*,
*::before,
*::after {
  box-sizing: border-box;
}

html {
  -moz-text-size-adjust: none;
  -webkit-text-size-adjust: none;
  text-size-adjust: none;
}

blockquote {
  margin: 0;
  padding: 1rem;
}

h1 {
  margin-block-start: 1.45rem;
  margin-block-end: 1.45rem;
}

h2 {
  margin-block-start: 1.25rem;
  margin-block-end: 1.25rem;
}

h3 {
  margin-block-start: 1.175rem;
  margin-block-end: 1.175rem;
}

h4 {
  margin-block-start: 1.15rem;
  margin-block-end: 1.15rem;
}

figure {
  margin: 0;
}

p {
  margin-block-start: 1rem;
  margin-block-end: 1rem;
}

ul[role='list'],
ol[role='list'] {
  list-style: none;
}

body {
  margin: 0;
  min-height: 100vh;
  line-height: 1.5;
  font-family:
    Arial,
    ui-sans-serif,
    system-ui,
    -apple-system,
    BlinkMacSystemFont,
    sans-serif;
  font-size: 16px;
}

h1,
h2,
h3,
h4,
button,
input,
label {
  line-height: 1.1;
}

h1,
h2,
h3,
h4 {
  text-wrap: balance;
}

a:not([class]) {
  text-decoration-skip-ink: auto;
  color: currentColor;
}

img,
picture {
  max-width: 100%;
  display: block;
}

input,
button,
textarea,
select {
  font: inherit;
}

textarea:not([rows]) {
  min-height: 10rem;
}

:target {
  scroll-margin-block: 5ex;
}

Reset will be placed in styles.scss.

Edit index.html:


  
    <meta charset="utf-8">
    <title>BuyAndFly</title>
    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
    <meta name="description" content="Example Angular 18 application for search for cheap flights and hotels.">
    <link rel="preconnect" href="https://photo.hotellook.com">
    <link rel="apple-touch-icon" sizes="180x180" href="/favicons/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/favicons/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/favicons/favicon-16x16.png">
    <link rel="manifest" href="/site.webmanifest">
    <link rel="mask-icon" href="/favicons/safari-pinned-tab.svg" color="#172659">
    <meta name="msapplication-config" content="/browserconfig.xml">
    <meta name="msapplication-TileColor" content="#172659">
    <meta name="theme-color" content="#ffffff">
  
  
       <baf-root></baf-root>
  

Add the generated favicons to public, as well as other files:

browserconfig.xml:

<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
    <msapplication>
        <tile>
            <square150x150logo src="/favicons/mstile-150x150.png"></square150x150logo>
            <tilecolor>#172659</tilecolor>
        </tile>
    </msapplication>
</browserconfig>

site.webmanifest:

{
    "name": "Buy & Fly",
    "short_name": "Buy & Fly",
    "icons": [
        {
            "src": "/favicons/android-chrome-192x192.png",
            "sizes": "192x192",
            "type": "image/png"
        },
        {
            "src": "/favicons/android-chrome-512x512.png",
            "sizes": "512x512",
            "type": "image/png"
        }
    ],
    "theme_color": "#ffffff",
    "background_color": "#ffffff",
    "display": "standalone",
    "start_url": ".",
    "description": "Search for cheap flights and hotels.",
    "categories": ["travel", "education"],
    "screenshots": [
      {
        "src": "screenshot.webp",
        "sizes": "1280x720",
        "type": "image/webp"
      }
    ]
}

robots.txt:

User-agent: *
Disallow: /api

User-agent: Yandex
Disallow: /api
Clean-param: bonus&utm_source&utm_medium&utm_campaign&utm_term&utm_content&click_id&appstore&platform

Host: https://buy-and-fly.fafn.ru
Sitemap: https://buy-and-fly.fafn.ru/sitemap.xml

At the end we use the layout in src/app/app.routes.ts:

import { Routes } from '@angular/router';

export const routes: Routes = [
  {
    path: '',
    loadComponent: () => import('@baf/ui/layout').then((m) => m.LayoutComponent),
    children: [],
  },
];

Launch the application:

yarn serve

We will see a white screen :)

Добавление шапки и футера

Создадим шапку и подвал:

yarn ng g c header
yarn ng g c footer

Перенесем в ui/layout и экспортируем:

export * from './lib/footer/footer.component';
export * from './lib/header/header.component';
export * from './lib/layout.component';

Подключим их в приложении:

import { Routes } from '@angular/router';

export const routes: Routes = [
  {
    path: '',
    loadComponent: () => import('@baf/ui/layout').then((m) => m.LayoutComponent),
    children: [
      {
        path: '',
        loadComponent: () => import('@baf/ui/layout').then((m) => m.HeaderComponent),
        outlet: 'header',
      },
      {
        path: '',
        loadComponent: () => import('@baf/ui/layout').then((m) => m.FooterComponent),
        outlet: 'footer',
      },
    ],
  },
];

Запустим проект:

yarn serve

Видим созданные компоненты.

В следующей статье добавим core сервисы и интерфейсы.

Ссылки

Все исходники находятся на github, в репозитории - github.com/Fafnur/buy-and-fly

Демо можно посмотреть здесь - buy-and-fly.fafn.ru/

Мои группы: telegram, medium, vk, x.com, linkedin, site

The above is the detailed content of Creating a Basic Framework for Angular 18. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use