Введение в angular

angular.json¶

Следующий шаг после установки Angular и изучения структуры «скелета» приложения — настройка. — главный конфигурационный файл так называемого Angular Workspace (директория my-app), сгенерированного с использованием и объединяющего в себе множество проектов (само приложение и созданные библиотеки для него).


Основные свойства:

  • — версия Angular Workspace;
  • — указывает, где будут располагаться внутренние приложения и библиотеки, по умолчанию projects;
  • — описание конфигураций для каждого из элементов Angular Workspace. По умолчанию вместе с основным генерируется проект с интеграционными тестами. Опции:
  • — определяет директорию с файлами, включая конфигурационные, всего проекта;
  • — определяет директорию с исходными файлами;
  • — тип проекта, может быть только или ;
  • — префикс, который будет использоваться при именовании компонентов и директив;
  • — позволяет задавать отличную от по умолчанию конфигурацию сущностей Angular, например, можно для всех создаваемых компонентов переопределить работу механизма Change Detection;
  • — используется для настройки запуска или сборки.
  • — имя проекта, который будет использоваться при использовании команд Angular CLI (по умолчанию основной).

Рассмотрим подробно в параметр свойства . Здесь нас интересуют и .

В указываются следующие опции:

  • — путь, где будет находиться «собранный» проект (подробно о сборке здесь);
  • — путь к ;
  • — путь к ;
  • — путь к ;
  • — путь к ;
  • — массив с указанием путей к статическому контенту, могут быть папки или отдельные файлы;
  • — массив с указанием путей к стилям, причем стили распространяются на все приложение;
  • — массив с указанием путей к javascript-файлам, обычно здесь подключаются сторонние библиотеки, не являющиеся модулями Angular, например, jQuery.

Всегда подключайте сторонние скрипты и стили не в , а в .

В указываются настройки, связанные со средой окружения (environment, далее СО) работы приложения.

Каждое свойство объекта — название СО с объектом настроек среды в качестве значения.

СО указывается при запуске (сборке) в качестве параметра (краткая запись ).

В объекте настроек СО множество параметров, назначение большинства которых понятно из их названия. Остановимся на .

В директории по умолчанию находятся два файла: и . В них указываются параметры, зависящие от СО, например, адрес сервера, с которого будут запрашиваться данные. По умолчанию используется .

Объект, используемый в качестве значения , позволяет переопределить источник для указанной СО.

Можете открыть и найти соответствующий код.

A Glimpse into the Future

Angular CLI’s roadmap contains many exciting upcoming features:

  • progressive web app (PWA) support Angular CLI will be able to create a Web Application Manifest for you, generate an App Shell and provide Service Worker scripts to cache your application data.Learn more about mobile support here.
  • Refactoring Support In addition to adding features to your application, Angular CLI will also let you refactor existing features — for example, moving a component or renaming a service.
  • Upgrade Support Angular CLI will be able to help you with Angular upgrades. Because Angular CLI has a semantic understanding of your application, it will be able to help you with code changes that are required when upgrading to a newer version of Angular.
  • Extensibility Improved extensibility support so you can create your own custom add-ons and deployment scripts.
  • Increased Performance Improved performance so Angular CLI becomes faster.
  • Library Developer Mode In addition to creating a new application, Angular CLI will also let you create a new library that can be consumed by others.

Some of these features are already partially available. Check out the GitHub repository if you want to play around with them.

Usage

<inputtype="password"tr-trustpass>
<inputtype="password"tr-trustpass="{special: false}"ng-minlength="9">
<formname="demo"><divclass="form-group"ng-class="{'has-error': demoForm.password.$invalid && demoForm.password.$dirty,                                     'has-success': !demoForm.password.$invalid && demoForm.password.$dirty}"><labelfor="password">Password</label><inputid="password"class="form-control"type="password"name="password"placeholder="Password"tr-trustpass="{maximum: true, special: false, messageGuide: 'Make sure your password meets these requirements:'}"ng-minlength="9"ng-maxlength="90"ng-model="password"></div><buttontype="submit"ng-disabled="demo.password.$invalid"class="btn btn-primary">Sign in</button></form>

Using the CDN

With the Google CDN, you will not need to download local copies of the distribution files. Instead, reference the CDN URLs to use those remote library files. This is especially useful when using online tools such as CodePen, Plunker, or jsFiddle.

<head><linkrel="stylesheet"href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.24/angular-material.min.css"></head><body><scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular-animate.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular-aria.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular-messages.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.24/angular-material.min.js"></script></body>

Unit Testing with Angular Material

  • AngularJS mocks
  • AngularJS Material mocks

Shown below is a karma-configuration file () sample that may be a useful template for your testing purposes:

module.exports=function(config){varSRC='src/myApp/**/*.js','test/myApp/**/*.spec.js';varLIBS='node_modules/angular/angular.js','node_modules/angular-animate/angular-animate.js','node_modules/angular-aria/angular-aria.js','node_modules/angular-messages/angular-messages.js','node_modules/angular-material/angular-material.js','node_modules/angular-mocks/angular-mocks.js','node_modules/angular-material/angular-material-mocks.js';config.set({    basePath__dirname+'',    frameworks'jasmine',    filesLIBS.concat(SRC),    port9876,    reporters'progress',    colorstrue,    autoWatchfalse,    singleRuntrue,    browsers'Chrome'});};

Директория app¶

Теперь разберем подробно содержимое .

Минимально каждое приложение должно состоять из одного корневого модуля, содержащего обособленные функциональные части — компоненты. Также корневой модуль может обращаться к компонентам других модулей.

Архитектура детально описана в следующей главе.

Объявление корневого модуля находится в .

app.module.ts

Здесь импортируются все модули и компоненты приложения.

Декоратор создает корневой модуль, которому передается объект конфигурации со свойствами:

  • — используемые второстепенные модули Angular;
  • — все компоненты приложения;
  • — основной компонент, отвечающий за загрузку.

Название может быть любым, но общепринято использовать .

Основной компонент приложения — .

app.component.ts

За объявление компонента отвечает декоратор из . Принимаемый объект:

  • — название компонента;
  • () — HTML-разметка в виде строки (путь к HTML-файлу);
  • — массив путей к CSS-файлам, содержащим стили для создаваемого компонента.

Это не все свойства декоратора , полное описание здесь.

Хорошей практикой считается вынесение HTML-разметки в отдельные файлы.

Чтобы убедиться в работоспособности происходящего, из папки необходимо выполнить:


По умолчанию приложение запускается по адресу , а наличие параметра указывает на то, что после компиляции оно автоматически откроется в браузере.

Для указания другого порта используйте параметр .

Creating a New Angular Application

There are two ways to create a new application using Angular CLI:

  • : create a new application in the current directory
  • : create a new directory and run inside the new directory.

So is similar to , except that it also creates a directory for you.

Assuming you haven’t created a directory yet, let’s use to create a new project:

Behind the scenes, the following happens:

  • a new directory is created
  • all source files and directories for your new Angular application are created based on the name you specified () and best-practices from the official Angular Style Guide
  • npm dependencies are installed
  • TypeScript is configured for you
  • the Karma unit test runner is configured for you
  • the Protractor end-to-end test framework is configured for you
  • environment files with default settings are created.

You’ll learn more about each of these aspects in the following sections.

At this point you have a working Angular application and your new directory looks like this:

Available Options

  • : boolean, default , perform dry-run so no changes are written to filesystem
  • : boolean, default
  • : boolean, default , automatically link the package ()
  • : boolean, default , skip
  • : boolean, default , don’t initialize git repository
  • : boolean, default , skip creating tests
  • : boolean, default , skip committing the first git commit
  • : string, name of directory to create, by default this is the same as the application name
  • : string, default , name of source directory
  • : string, default , the style language to use (, or )
  • : string, default , the prefix to use when generating new components
  • : boolean, default , generate a Progressive Web App application (see section on )
  • : boolean, default , add module with routing information and import it in main app module
  • : boolean, default , use inline styles when generating the new application
  • : boolean, default , use inline templates when generating the new application.

Run to see all available options of your locally installed Angular CLI.

Let’s see how you can start your application so you can see it in action.

Summary

Angular CLI is a command-line interface (CLI) to automate your development workflow.

Today, you can already use Angular CLI to:

  • create a new Angular application
  • run a development server with LiveReload support to preview your application during development
  • add features to your existing Angular application
  • run your application’s unit tests
  • run your application’s end-to-end (E2E) tests
  • build your application for deployment to production
  • deploy your application to a server.

Although it’s technically not required to use Angular CLI to develop an Angular application, it can definitely improve the quality of your code and save you a lot of time and effort.

Because of the many exciting features that will be added over time, Angular CLI will probably become an indispensable tool for developing Angular applications.

To learn more about Angular CLI, check out the official website and the GitHub repository.

The Ultimate Angular CLI Reference Guide was peer reviewed by Tim Severien, Vildan Softic and Joan Yin. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

Rules

Rules in eslint-plugin-angular are divided into several categories to help you better understand their value.

The following rules detect patterns that can lead to errors.

These are rules designed to prevent you from making mistakes. They either prescribe a better way of doing something or help you avoid footguns..

These rules prevent you from using deprecated angular features.

These rules help you to specify several naming conventions.

Angular often provide multi ways to to something. These rules help you to define convention for your project.

These rules help you to enforce the usage of angular wrappers.

These rules help you avoiding misspellings.

on-destroy — Check for common misspelling $on(‘destroy’, …).

Development Hints for working on Angular CLI

git clone https://github.com/angular/angular-cli.gitcd angular-clinpm link

is very similar to except that instead of downloading the package from the repo, the just cloned folder becomes the global package. Additionally, this repository publishes several packages and we use special logic to load all of them on development setups.

Any changes to the files in the folder will immediately affect the global package, allowing you to quickly test any changes you make to the cli project.

Now you can use via the command line:

ng new foocd foonpm link @angular/cling serve

is needed because by default the globally installed just loads the local from the project which was fetched remotely from npm. symlinks the global package to the local package. Now the you cloned before is in three places: The folder you cloned it into, npm’s folder where it stores global packages and the Angular CLI project you just created.

You can also use to automatically link the package.

To run the Angular CLI test suite use the command. It can also receive a filename to only run that test (e.g. ).

As part of the test procedure, all packages will be built and linked. You will need to re-run to re-link the development Angular CLI environment after tests finish.

Running Your Application

To preview your new application in your browser, navigate to its directory:

and run:


to start the built-in development server on port 4200:

You can now navigate your favorite browser to http://localhost:4200/ to see your application in action:

Behind the scenes, the following happens:

  1. Angular CLI loads its configuration from
  2. Angular CLI runs Webpack to build and bundle all JavaScript and CSS code
  3. Angular CLI starts Webpack dev server to preview the result on .

Notice that the command doesn’t exit and return to your terminal prompt after step 3.

Instead, because it includes LiveReload support, the process actively watches your directory for file changes. When a file change is detected, step 2 is repeated and a notification is sent to your browser so it can refresh automatically.

To stop the process and return to your prompt, press .

Manual Initialization

Gets the functionality to operate on the editor: create, destroy and get editor instance. Use it if you want to manually initialize the editor.

Where is the name of a function in your component which will receive an object with different methods to control the editor initialization process.

publicinitialize(initControls){this.initControls=initControls;this.deleteAll=function(){this.initControls.getEditor()('html.set','');};}

The object received by the function will contain the following methods:

  • initialize: Call this method to initialize the Froala Editor
  • destroy: Call this method to destroy the Froala Editor
  • getEditor: Call this method to retrieve the editor that was created. This method will return null if the editor was not yet created

Usage

<gojs-diagramdivClassName]='myDiagramDiv'initDiagram]='initDiagram'nodeDataArray]='diagramNodeDataArray'linkDataArray]='diagramLinkDataArray'modelData]='diagramModelData'  (modelChange)='paletteModelChange($event)'skipsDiagramUpdate]='skipsDiagramUpdate'></gojs-diagram><gojs-palettedivClassName]='myPaletteDiv'initPalette]='initPalette'nodeDataArray]='paletteNodeData'></gojs-palette><gojs-overviewinitOverview]='initOverview'divClassName]='myOverviewDiv'observedDiagram]='observedDiagram'></gojs-overview>

Specifies a function that is reponsible for initializing and returning a GoJS Diagram, Palette, or Overview. In the case of an Overview, this is an optional property and when not provided, an Overview with default properties and centered content will be created.

functioninitDiagram(){const$=go.GraphObject.make;constdiagram=$(go.Diagram,{'undoManager.isEnabled'true,      model$(go.GraphLinksModel,{        linkKeyProperty'key'})});diagram.nodeTemplate=$(go.Node,'Auto',$(go.Shape,'RoundedRectangle',{ strokeWidth, fill'white'},newgo.Binding('fill','color')),$(go.TextBlock,{ margin8},newgo.Binding('text','key')));return diagram;}

Specifies the CSS classname to add to the rendered div. This should usually specify a width/height.

.myDiagramDiv{width400px;height400px;border1pxsolidblack;}

Specifies the array of nodes for the Diagram’s model.

nodeDataArray{ key'Alpha', color'lightblue'},{ key'Beta', color'orange'},{ key'Gamma', color'lightgreen'},{ key'Delta', color'pink'}

Specifies the array of links for the Diagram’s model.

linkDataArray{ key-1, from'Alpha', to'Beta'},{ key-2, from'Alpha', to'Gamma'},{ key-3, from'Beta', to'Beta'},{ key-4, from'Gamma', to'Delta'},{ key-5, from'Delta', to'Alpha'}

Specifies a modelData object for the Diagram’s model.

Specifies a function to be called when a GoJS transaction has completed. This function will typically be responsible for updating app-level state.

publicdiagramModelChange=function(changesgo.IncrementalData){this.diagramNodeData=DataSyncService.syncNodeData(changes,this.diagramNodeData);this.diagramLinkData=DataSyncService.syncLinkData(changes,this.diagramLinkData);this.diagramModelData=DataSyncService.syncModelData(changes,this.diagramModelData);};

Notice the use of the three functions of the DataSyncService, which is included with this package to make syncing your app-level data with Diagram / Palette data simple.

Specifies whether the component should skip updating, often set when updating state from a GoJS model change.

Specifies the go.Diagram which the Overview will observe.

About

Designed around KISS Principle Keep it simple stupid

  1. Accept all parameters that Semantic UI does and extends with some angular features.
  2. Pass data in variables and objects (don’t clutter html, use controller and services)
  3. Call Semantic UI js code as much as possible: Why reinvent the wheel!
  4. Semantic UI syntax looks good with angular, no need to have directive to add html classes unless really nessesary or simpifies significantly
  5. Follow from last two points :If there is no Semantic UI js code, there needs to be a real benefit to write angular code.
  • AngularJS
  • semantic UI
  • jQuery

I have written directive as I have needed the modules, which mean they are used live and work. If you request a directive please allow a week for me to write it.

Please put an issue if you intend to contribute your work, then I will put some effort to write the rules and guidlines etc.

Backlog Planned Done Not Planned
Dimmer Accordian Dropdown Checkbox *
Embed Modal Nag *
Progress Popup Tab *
Rating Sidebar
Search** Sticky
Shape
Transition**
Visibility API *
Form Validation *
Elements ***
Collections ***

* Found AngularJS out of the box does the job well enough ** Not sure if AngularJs is better suited or not **** No javascript, so no plans unless there is a compelling reason

Load the Module

Use to load the module. E.g.

angular.module('app','uiAngular');

All object are initiated if needed to. E.g.

$('.classes').method();

vm.directiveObject Dom instance object to be used for Semantic UI usage. E.g.

vm.directiveObject.method('show');

vm.directiveData Semantic UI settings object. E.g.

vm.directiveData={  on'hover',onShowfunction(){...}};

Warning: Setting the variables for the method through javascript/jquery syntax will in many cases render the useless, i.e.

$('.classes').method({ setting value});vm.directiveObject.method({ setting value,callBackfunction(){...}});

Building Your Application for Production

Running builds and bundles your Angular application automatically to a virtual filesystem during development.

However, when your application is ready for production, you’ll need real files that you can deploy to your server or to the cloud.

To build and bundle your application for deployment, run:

The output of the command is sent to your console:

This is what happens behind the scenes:

  1. Angular CLI loads its configuration from .
  2. Angular CLI runs Webpack to build and bundle all JavaScript and CSS code.
  3. The result is written to the directory specified in your Angular CLI configuration. By default, this is the directory.

Available options

  • : enable ahead-of-time compilation
  • : string, the base href to use in the index file
  • : string, default , environment to use
  • : string, directory to write the output to
  • : string, default , environment to use
  • : boolean, default , watch files for changes and rebuild when a change is detected.

Targets

Specifying a target impacts the way the build process operates. Its value can be one of the following:

  • : default mode, do not minify or uglify code
  • : minify and uglify code.

Building your application in production mode:


This results in bundles that are minified, uglified and have hashes in their names:

Environments

Environments let you specify settings to customize your application behavior.

You can define your own environments in the file. The default ones are:

  • : use settings defined in
  • : use settings defined in
  • : use settings defined in .

Here, equals:

And equals:

The build process will use the environment by default.

If you specify a different environment, the build process will use the corresponding environment:

As you can see in , you can access the environment settings from your code by importing :

The build process will make sure the right environment is provided when you import it.

Using the AngularJS Material Library

You have installed the AngularJS library, next include the scripts and stylesheet in your main HTML file, in the order shown in the example below. Note that NPM will install the files under .

<!DOCTYPE html><html><head><metaname="viewport"content="initial-scale=1, maximum-scale=1, user-scalable=no" /><linkrel="stylesheet"href="/node_modules/angular-material/angular-material.css"></head><bodyng-app="YourApp"><divng-controller="YourController"></div><scriptsrc="/node_modules/angular/angular.js"></script><scriptsrc="/node_modules/angular-aria/angular-aria.js"></script><scriptsrc="/node_modules/angular-animate/angular-animate.js"></script><scriptsrc="/node_modules/angular-messages/angular-messages.js"></script><scriptsrc="/node_modules/angular-material/angular-material.js"></script><script>angular.module('YourApp','ngMaterial','ngMessages').controller("YourController", YourController);</script></body></html>

Running Your Unit Tests

Angular CLI automatically configures the Karma test runner for you when your application is initially created.

When adding a feature to your application, you can use the option to specify whether you want Angular CLI to also create a corresponding file with a sample unit test for your new feature.

Spec files are created in the same directory of their corresponding feature in the directory. This allows you to easily locate them when working on a feature.

Running all unit tests of your application thus implies running all unit tests specified in all files ending in in all directories inside your directory.

To run all unit tests, run:

The following output will appear in your console:

A special browser instance will also be launched:

Here’s what happens behind the scenes:

  1. Angular CLI loads .
  2. Angular CLI runs Karma with the configuration specified in . By default this is located in the root directory of your application.
  3. Karma opens the browser specified in the Karma configuration. By default the browser is set to Google Chrome.
  4. Karma then instructs the browser (Chrome) to run using the testing framework specified in the Karma config. By default this is the Jasmine framework. The file is automatically created when your application is created. It’s pre-configured to load and configure the code that’s needed to test your Angular application and run all spec files ending in in your directory.
  5. Karma reports the result of the test run to the console.
  6. Karma watches the file for changes and repeats step 4 and 5 when a file change is detected.

To end the process, you can press .

If you want to learn more about testing your Angular code, you can check out the Official Angular Testing Guide.

📁 Configuration File

To avoid all these command-line cmd options, you can write down your configuration in the file in the attribute of your deploy project’s architect. Just change the kebab-case to lower camel case. This is the notation of all options in lower camel case:

  • baseHref
  • configuration
  • noBuild
  • repo
  • message
  • branch
  • name
  • email
  • noSilent
  • noDotfiles
  • cname
  • dryRun

Example:

ng deploy --base-href=https://angular-schule.github.io/angular-cli-ghpages/ --name="Angular Schule Team" --email=team@angular.schule

becomes

"deploy"{"builder""angular-cli-ghpages:deploy","options"{"baseHref""https://angular-schule.github.io/angular-cli-ghpages/","name""Angular Schule Team","email""team@angular.schule"}}

And just run .

How to create a new rule

We appreciate contributions and the following notes will help you before you open a Pull Request.

Have a look at the existing issues. There may exist similar issues with useful information.

There are some useful references for creating new rules. Specificly useful are:

    • JavaScript file with the new rule
    • The filename is exactly the usage name in eslint configs
    • Have a look at the wrapper and the (both in ) — they probably make things easier for you
    • Add a documentation comment to generate a markdown documentation with the task
    • Write some tests and execute them with
    • Have a look at the coverage reports
    • Add some examples for the documentation
    • Run the task to test the examples and update the markdown documentation
  • Check that the task is working
  • Commit generated changes in and
  • Open your PR to the branch NOT

We can use a property, defined in the ESLint configuration file, in order to know which version is used : Angular 1 or Angular 2. based on this property, you can create rules for each version.

plugins-angularrulesangular/controller-name- 2-'/.*Controller$/'globalsangulartruesettingsangular 2

And in your rule, you can access to this property thanks to the object :

if(context.settings.angular===2){return{};}return{'CallExpression'function(node){}};

С этим читают