Angular – Stepan Suvorov Blog https://stepansuvorov.com/blog Release 2.0 Thu, 23 May 2019 15:07:25 +0000 en-US hourly 1 https://wordpress.org/?v=6.3.1 ngEurope2018. brief review. https://stepansuvorov.com/blog/2018/02/ngeurope2018-brief-review-keep-updating/ https://stepansuvorov.com/blog/2018/02/ngeurope2018-brief-review-keep-updating/#respond Sun, 04 Feb 2018 14:52:06 +0000 http://stepansuvorov.com/blog/?p=3502 Continue reading ]]>

Just to have less confusion I would like to say that there were no ngEurope2017, it was ngEurope2016 in October and next one was ngEurope2018 in February.

Manfred Steyer – High-Performance Applications with Angular (video)

  • Lazy loading
  • OnPush
  • AOT + TreeShaking(with build optimizer)
    • new AOT compiler is coming
  • Service Workers for caching (did not cover)

Erik Haddad – PWA Angular and Firebase (video)

  • what is Angular
  • what is PWA
  • what is firebase
    • auth
    • database
    • storage
    • cloud functions
  • AngularFire2
    • * new AngularFireStorage
  • Firechat

Christian Liebel – On the road to PWA: building real-cross platform Angular apps with Cordova & Electron (video, code)

real cross-platform:

  • single codebase
  • maximum code reuse

What is PWA?

Native App Packaging: Cordova and Electron.

Demo session to show how DI works for different devices based on env.

Stefanie Trimble Fluin – Creating Beautiful Experiences Fast with Angular Material (video)

  • material design
  • angular material
    • basic intro how to use the library
  • theming
  • CDK (was not covered)

Antal Andrei – A look into the future: Angular Elements (video, slides, code)

  • need to have angular components outside angular
  • introduction of web components
  • Angular Elements – angular components packaged in web components
    • @angular/elements
    • ngDoBootstrap inside component
    • registerAsCustomElements

Relative video: Pascal Precht – Angular Elements (at ng-be)

Asim Hussain – How to hack an Angular app? (video)

Asim told us 3 hacker break-in stories that based on simple things.

Story1: Github story

git hook to localhost -> http://0:9200/_shutdown -> http://0:email -> memcache -> deprecated python library

moral: don’t underestimate small things

Story2: Equifax

moral: use latest versions of your software to be sure that there are no known vulnerabilities

Story3:

About cross-env fake npm package

moral: don’t trust npm by default, there are fake npm packages.

nsp – tool to check for package version

Todd Motto – Angular Architecture: From Patterns to Implementation. (video)

Todd tried to show an example of real-world objects and their communication to describe Redux(or ngRx) logic and high-level component/modules architecture.

Sean Larkin – webpack4: most important update for Angular  (video)

Quite inspiring one!

  • smaller and faster builds
    • new plugin system
      • hooks are now monomorphic
  • modernization
  • developer experience
    • RIP commonChunck plugin

Adam Bradley – Next Generation Ionic: Built for PWAs and interoperability (video)

From the beginning, I have a feeling that it was a paid talk from a sponsor.

  • ionic uses customElements (the same as Angular Elements)
  • need to have a look at stenciljs (it’s still unclear after the talk)
  • lazy loading on component level

Sven Sauleau – Let’s compose JavaScript and Reason (video)

It was quick intro with simple examples of Reason power over types. If you are about to start with Reason I strictly recommend to watch this talk.

Mashhood Rastgar – Rapid prototyping using Angular and Firebase (video)

Mashhood was showing a live coding doing a twiter clone with Firebase: database and auth. The whole app to create and deploy took him only 12min!  If you want to start working with Firebase services check the video.

Jen Looper – Boost Your App’s Emotional Intelligence with NativeScript, Angular and Machine Learning (video)

IMHO, the most inspiring talk of the conference. It was a combination of IoT, AI, and NativeScript.

After this talk, I already want to buy some IoT sensors and start building NativeScript to manage them.

 

]]>
https://stepansuvorov.com/blog/2018/02/ngeurope2018-brief-review-keep-updating/feed/ 0
ngx-wig: 1.0.0 https://stepansuvorov.com/blog/2018/01/ngx-wig-1-0-0/ https://stepansuvorov.com/blog/2018/01/ngx-wig-1-0-0/#respond Fri, 26 Jan 2018 19:15:33 +0000 http://stepansuvorov.com/blog/?p=3497

ngx-wig – opensource lightweight WYSIWYG editor for Angular.

I’ve just merged pull request with tests and we are ready to go.

Finally, release!

P.S.: thanks a lot @bampakoa for the contribution!

]]>
https://stepansuvorov.com/blog/2018/01/ngx-wig-1-0-0/feed/ 0
ng-be 2017. brief review https://stepansuvorov.com/blog/2017/12/ng-be-2017-brief-review/ https://stepansuvorov.com/blog/2017/12/ng-be-2017-brief-review/#respond Sat, 09 Dec 2017 17:54:12 +0000 http://stepansuvorov.com/blog/?p=3480 Continue reading ]]>

Pascal Precht – Angular Elements  (video, slides, code )

Angular Elements is very experimental from Angular Labs. Reference to Rob Wormald’s talk “A Glimpse at Angular Elements“.

Why do we need it? It’s still tricky to use Angular outside of Angular applications for:

  • reusability
  • CMS pages
  • widgets

WebComponents could help to achieve this. Then Pascal made a quick introduction of main parts of web components: templates, html imports, shadow DOM and custom elements:

CustomElements pretty close to Angular Components:

@HostBinding() Attributes
@Input() Properties
@Output() CustomEvent()
Lifecycle Hooks Reactions

so.. Angular Elements – Angular Components packaged into Custom Elements:

  • self-bootstrapping
  • Hosts Angular Component inside Custom Element
  • Bridges DOM APIs and Angular APIs

and then it was a life coding with Hello World and Material Components examples.

P.S.: 2 or 3  years ago we have implemented the same concept for AngularJs, React and Backbone wrapped into CustomElements, you can check it here.

Uri Shaked – Static website with Angular (video, slides, code )

Uri did a lot of life coding from scratch.

the goal:

  • component-based architecture
  • content shows immediately
  • no server-side code

Project from scratch step-by-step:

  • dependencies
  • app skeleton
  • module definition
  • a component with a template

for this moment we’ve done with a part that usually CLI does for us

But after it was something really nice:

We used Fuse-Box instead of webpack and I was impressed by the speed of recompilation.

We integrated Angular Universal rendering, but not for server-side prerendering, but only for first compilation to provide page immediately. So server-side rendering without a server. I like the idea, but unfortunately not very useful when your data is constantly updating and you have routes.

Some nice extra resources:

Juri Strumpflohner – Create and publish Angular libs like a Pro (video, slides)

It’s great that question that I asked Igor Minar previous ng-be now was represented in such a detailed way by Juri.

Main parts:

  • there is already an Angular Package Format
  • take care of PeerDependencies
  • inline your assets (templates, css)
  • FESM – literally put all in one file (or a single ES Module)
  • compile into different formats(umd, es5, es2015) and specify paths in package.json

After Juri recommended some nice tools to automate the process:

and ready package managers to do all the work:

and keep eye on Angular CLI Schematics!

Vincent Ogloblinsky‏ – Hidden gems of TS compiler (video, slides)

First Vincent explained what regular compiler does, and it:

  • parsing
    • lexical analysis
    • syntax analysis
  • transforming
  • generation

TS is doing quite the same:

  • scanner
  • parser
  • binder
  • checker
  • emitter

What else we can do with AST?

  • linting
  • complexity check
  • docs
  • API

Some nice tools to check:

I think the main thing of that presentation was

 

Philippe De Ryck – Cookies versus tokens: a paradoxical choice (video)

Philippe never ceases to amaze me by uncovering hidden parts of obvious (from the first look) topic – sessions.

The talk was divided into 3 parts:

  • where to store the data (locality):
    • old school sessions (server side)
    • JSON Web Tokens (client side)
      • !important: don’t forget to verify the key! (not just decode the data)
  • how to store
    • cookies
    • auth headers
      • not handled automatically (and not present on all the requests) 
      • do not enable  Cross-Site Request Forgery   ✔
      • easy to support outside a browser    ✔
      • looks secure  ✔
        • don’t forget about whitelist implementing angular interceptors (18:08)
  • how to transport
    • cookie – httpOnly
    • localStorage – not secure enough  
    • sessionStorage ✔

Maxim Salnikov – Creating an Angular Progressive Web App (video, slides)

The whole Maxim’s presentation I had a feeling that I’m watching a video on x2 speed.

Starting from angular-cli 1.6 you can create your Angular application with ServiceWorkers by one command:

ng new app --service-worker

Unfortunately, you cannot use webpack dev server, so you need to build it first:

ng build --prod

and then run with a static web server on dist folder (I use http-server for it):

http-server ./dist

still does not work with ng-cli server :(

register NGSW: import ServiceWorkerModule

caching strategies: freshness vs performance

 

Manfred Steyer – Angular’s new HttpClient (video, slides)

  • custom data formats
    • work with XML
  • progress information
    • by subscribing to an event
  • interceptors for extensions

and lot of life coding with Interceptors…

Aimee Knight – Pulling Back the Curtains From Your Stylesheets (video)

Aimee presented low-level browser html/css life cycle.

binary -> text -> tokenizer -> parser -> tree structure (DOM)

…lots of text on slides that had been just read…

Asim Hussain – How to hack an Angular app? (video, slides)

Asim told us 3 hacker break-in stories that based on simple things.

Story1: Github story

git hook to localhost -> http://0:9200/_shutdown -> http://0:email -> memcache -> deprecated python library

moral: don’t underestimate small things

Story2: Equifax

moral: use latest versions of your software to be sure that there are no known vulnerabilities

Story3:

moral: don’t trust npm by default, there are fake npm packages.

Dominic Elm – Taming snakes with reactive streams (video, slides)

Why reactive?

  • dom events
  • http requests
  • web sockets
  • animations

How to think reactively?

No side effects!

Approach

  1. split into small parts
  2. define a trigger
  3. compose all together

Ayşegül Yönet – Performant Augmented Reality for the Web (video, slides)

Some information about VR and AR.

Technologies to achieve – WebGL & WebRTC

Libraries – Three.ar.js

Switch ngZone for all project (not to run for each rendering)- now possible with ng5:

bootstrapModule(AppModule, { ngZone: ‘noop’})

Todd Motto – Angular Architecture: From Patterns to Implementation (video, slides)

Toooo architectural abstraction with pizza restaurant at the end of the day…

]]>
https://stepansuvorov.com/blog/2017/12/ng-be-2017-brief-review/feed/ 0
View encapsulation и другие опции компилятора https://stepansuvorov.com/blog/2017/07/view-encapsulation-off/ https://stepansuvorov.com/blog/2017/07/view-encapsulation-off/#respond Fri, 28 Jul 2017 13:56:03 +0000 http://stepansuvorov.com/blog/?p=3424 Continue reading ]]> Это крайне не рекомендовано, но, тем не менее, иногда приходится глобально выключать инкапсуляцию стилей. Чтобы этого достичь мы можем воспользоваться настройками при бутстрапе модуля, то есть вместо:

platformBrowserDynamic().bootstrapModule(AppModule);

сделать:

View the code on Gist.

Полный список параметров компиляции, которые мы можем менять при инициализации модуля:

  • useDebug – включение дебаг режима (и уже деприкейтед начиная с v4)
  • useJit – переключатель режима: Codegen и Interpretative (не путать с AOT/JIT), по умолчанию работает кодогенерация.
  • defaultEncapsulation – задает инкапсуляцию стилей по умолчанию (то что мы сделали выше)
  • providers – переопределение провайдеров для компилятора COMPILER_PROVIDERS (вы не можете сделать тоже самое в ngModule, так как компилятор использует свой собственный инжектор)
  • missingTranlsations – задает стратегию поведения при отсутсвующих переводах
  • enableLegacyTemplate – чтобы продолжать поддерживать тег template
]]>
https://stepansuvorov.com/blog/2017/07/view-encapsulation-off/feed/ 0
Новое в Angular4.3 https://stepansuvorov.com/blog/2017/07/%d0%bd%d0%be%d0%b2%d0%be%d0%b5-%d0%b2-angular4-3/ https://stepansuvorov.com/blog/2017/07/%d0%bd%d0%be%d0%b2%d0%be%d0%b5-%d0%b2-angular4-3/#comments Wed, 26 Jul 2017 18:36:08 +0000 http://stepansuvorov.com/blog/?p=3420 Continue reading ]]>
  • HttpClient – принципиально новый клиент, который переехал из отдельного модуля в подсекцию common (‘@angular/common/http‘):
    • позволяет получить данные сразу в JSON
    • типизировать возвращаемые данные вывод
    • появляются интерсепторы
    • задание дефолтных заголовков (например токена авторизации)
    • подписаться события прогресса
  • Новые гарды роутера: GuardsCheckStart, GuardsCheckEnd, ResolveStart, ResolveEnd, NavigationStart
  • Опция для отключения анимации в детях
  • Специальный CSS селектор ::ng-deep, который является альтернативой >>>
  • ]]>
    https://stepansuvorov.com/blog/2017/07/%d0%bd%d0%be%d0%b2%d0%be%d0%b5-%d0%b2-angular4-3/feed/ 1
    Angular: Что такое forwardRef? https://stepansuvorov.com/blog/2017/07/angular-%d1%87%d1%82%d0%be-%d1%82%d0%b0%d0%ba%d0%be%d0%b5-forwardref/ https://stepansuvorov.com/blog/2017/07/angular-%d1%87%d1%82%d0%be-%d1%82%d0%b0%d0%ba%d0%be%d0%b5-forwardref/#respond Sat, 15 Jul 2017 18:13:12 +0000 http://stepansuvorov.com/blog/?p=3416 Continue reading ]]> Мы иногда встречаем в коде:

    View the code on Gist.

    и сразу не понятно, что это магическая функция forwardRef. На самом деле все просто: forwardRef – это функция-обертка. Зачем она нужна? Чтобы мы могли задавать значением свойства сущности, которые объявлены ниже (иначе будет ошибка):

    View the code on Gist.

    Также можно глянуть в исходники, и убедиться что это просто метод-обертка:

    View the code on Gist.

    ]]>
    https://stepansuvorov.com/blog/2017/07/angular-%d1%87%d1%82%d0%be-%d1%82%d0%b0%d0%ba%d0%be%d0%b5-forwardref/feed/ 0
    AngularCamp 2017, notes https://stepansuvorov.com/blog/2017/07/angularcamp-2017-notes/ https://stepansuvorov.com/blog/2017/07/angularcamp-2017-notes/#respond Fri, 07 Jul 2017 17:50:24 +0000 http://stepansuvorov.com/blog/?p=3399 Continue reading ]]>

    I had I chance to visit AngularCamp these days and would like to share some thoughts/notes with you.

    Todd Motto & James Henry – From imperative to reactive thinking (slides)

    Todd showed 2 great examples of streams of real world.

    Bulbs that subscribed to one switch:

    and coffee machine that makes different sorts of coffee out of water:

    Next part was about comparing Imperative and Reactive approaches base on “game of throwing the ball” implementation.

    Well… IMHO

    Imperative: too much code, really difficult to follow

    Reactive: got lost even knowing how to work with Rxjs

     

    Dmitriy Shekhovtsov – Unleash The Power Of Angular With Knowledge of Patterns

    Dmitriy started naming the patterns that everybody knows: singleton, factory, pub/sub, adapter to warmup audience, after continued with: DI, module, IoC,  CQRS to make some JS developers exited about new words.

    Then he presented Dependancy injection pattern and provided 2 examples: with a fridge where parents “inject” food for the child and with carbonara that you don’t need to take care about ingredients. Frankly speaking, both examples highlighted an encapsulation principle more than DI. After he should how Angular code would look like without DI. I think it would be better to highlight the power of flexibility that DI provides you, instead of showing that

    Module pattern was next one. Dmitriy highlighted that even with EcmaScript2015+ with native modules we still have to compile it to an old school function wrapper. Some good reasons why to use this pattern:

    • namespaces
    • encapsulation
    • structured code
    • manage dependancy

    and after he compared it to ngModules: import, export, providers.

    Also Dmitriy provided interesting idea to split you SharedModule into 2: to put all you services separately. In this case you would not need forRoot/forChild approach.

    Next one was a Change Detection pattern. Some explanation about Javascript types and memory allocation, and “why the code worked in AngularJs and doesn’t work in Angular“. The answer is strict equality.

    Several more words about immutability, pure functions and single responsibility.

    Simona Cotin & Artur Daschevici – From Angular to React and back again

    Simona and Artur provided kind of comparison for Angular and React(yes, yet another comparison ;) )

    Simona started with Angular history, and told us what things had pushed AngularJs to be Angular:

    • ES6
    • Web components
    • React
    • RxJS
    • Typescript
    • EmberCli

    and also, of course, it was a time for performance changes. so now we have:

    • lazy loading
    • AoT
    • tree shaking

    Then Artur took the floor and told us some parts of React:

    • component based
    • predictable state management
    • ES6
    • Flow
    • Virtual DOM

    Then they compared CLI tools and component declaration and tools for each framework.

    Issues Angular:

    • migration
      • Angular Style Guide
      • TypeScript
      • UpgradeModule
      • Upgrade cheatsheet

    issues React:

    • unmanageble large app
    • state management
    • no unified way of doing things

     

    Victor Savkin – State Management Patterns and Best Practices with NgRxb

    too much code for 4th talk without break… it looked like Viktor wanted to put 4 hours talk in 40 minutes….

    * I’ll rewatch video one more time and will return back to you with more information about this topic.

    Also Victor several times during the talk recommended this book:

     

    Martin Splitt – Virtual Reality with A-Frame

    Quite inspiring talk: Martin not only showed how to make VR in Javascript with help of simple library but also make all audience laugh.

    He started with some examples of VR

    Compared different modern VR devices.

    Explained How VR works.

    I a bit of VR live coding with a-frame library.

     

    Filip Bech-Larsen – Building dynamic SPA website

    Filip showed results of his research how to build Angular over existing CMS: to use all management tools for content creation and editing and same time present it like SPA.

    Pascal Precht – Angular and Service Workers

    Progressive web apps (lighthouse – to check whether you app is progressive enough)

    Service workers

    Angular Service Worker

    • install @angular/serviceworker
    • angular-cli  serverWorker: true
    • sw-register
    • ngsw-manifest
    • dynamic routing

    Carmen Popoviciu – A moment’s reflection

    Deep psychological talk about developer beings from Carmen that was nicely combined with Martin Splitt jokes.

     

     

    ]]>
    https://stepansuvorov.com/blog/2017/07/angularcamp-2017-notes/feed/ 0
    Формы и валидация данных в Angular https://stepansuvorov.com/blog/2017/07/angular-forms-and-validation/ https://stepansuvorov.com/blog/2017/07/angular-forms-and-validation/#comments Sat, 01 Jul 2017 14:27:40 +0000 http://stepansuvorov.com/blog/?p=3382 Continue reading ]]> В отличии от AngularJS в Angular сделали целый модуль, который помогает в обработке форм.

    Angular предлагает 2 подхода работы с формами:

    • основанный на шаблонах (template-driven)
    • реактивный (reactive)

    Шаблонный более традиционный для декларативного подхода фреймворка. Реактивный появился позже и считается более прогрессивным и гибким. Мы разберем оба подхода.

    Подключение модуля форм

    Для начала работы с формами необходимо подключить модуль форм(FormsModule):

    import { FormsModule } from '@angular/forms';

    если мы хотим работать в реактивном подходе, то подключаем модуль ReactiveFormsModule:

    import { ReactiveFormsModule } from '@angular/forms';

    И конечно импортируем их в наш основной модуль:

    View the code on Gist.

    Шаблоно-ориентированный подход (template-driven)

    В шаблонно ориентированном подходе мы по большей части оперируем 3мя сущностями: ngModel, ngModelGroup и ngForm.

    ngModel

    Чтобы привязать данные к элементу формы мы можем поставить директиву ngModel:

    <input type="text" [ngModel]="name">

    Есть 3 способа как получить введенные данные:

    • двухстороннее связывание
    • обработку события изменения
    • ссылку на элемент (либо ngModel)

    ngModel и двухстороннее связывание (two way binding)

    Способ, который пришел из AngularJs и в Angular практически не используется, но тем не менее, его хорошо знать:

    <input type="text" [(ngModel)]="name">

    то есть вы используете специальный синтаксис двойных скобок: сначала прямоугольные, затем круглые ( чтобы было проще запомнить последовательность используется подсказка “коробка с бананами” )

    Теперь при вводе данных в элемент формы у нас будет обновляться и свойство контроллера name.

    ngModel и обработка события

    Вы можете использовать как родное событие поля ввода, например: для type text это будет input:

    <input type="checkbox" [ngModel]="name" (input)="name = $event.target.value">

    так и использовать специальное событие ngModelChange:

    <input type="text" [ngModel]="name" (ngModelChange)="name = $event">

    ngModel и обращение по ссылке

    Чтобы поставить ссылку на ngModel, мы делаем следующее:

    <input type="text" [ngModel]="name" #name>

    теперь мы можем обратиться в шаблоне к значению свойства элемента:

    {{name.value}}

    либо в контроллере компонента через специальный декоратор ViewChild:

    View the code on Gist.

    Также мы можем сделать ссылку не только на элемент, но и на сам контроллер ngModel:

    <input type="text" [ngModel]="name" #nameModel="ngModel">

    Теперь в nameModel нам доступно не только значение модели, но и все дополнительные свойства и методы контроллера модели:

    nameModel.valid

    Валидация данных в шаблонном подходе

    Полностью(или почти полностью) поддерживаются HTML5 валидация. То есть, например, если проставить полю атрибут require, то Angular его подхватит.

    Свои валидаторы в шаблонном подходе

    Не самый очевидный способ предлагают нам разработчики ангуляра для того, чтобы расширить валидаторы в шаблонном подходе. Мы должны создать директиву, в которой переопределить набор стантартных валидаторов NG_VALIDATORS, точнее дополнить своим(своими) с помощью флага multi:

    View the code on Gist.

    таким образом мы создали свой валидатор, который проверит не является ли значение равным ‘3’. Плюс попрошу обратить ваше внимание на селектор для директивы мы указали не только сам атрибут имени директивы, но также что на элементе будет присутствовать ngModel.

    Свои асинхронные валидаторы в шаблонном подходе

    Полностью идентичны синхронным, отличие только в том что ваш метод валидации возвращает Promise либо Observable, а прописывается не в NG_VALIDATORS, в а NG_ASYNC_VALIDATORS:

    View the code on Gist.

    Вывод ошибок

    Чтобы вывести ошибки также можем обратиться к контроллеру ngModel по ссылке и получить его свойство errors:

    {{nameModel.errors | json}}

    .

    …и теперь…

    .

    Реактивный (reactive) подход

    Реактивном подходе мы настраиваем элементы формы не в шаблоне, а в контроллере, оперируя при этом следующими понятиями: FormControl, FormGroup, FormArray, FormBuilder.

    На каждый элемент формы создается(вручную или автоматически) свой FormControl.

    FormControl

    Чтобы создать FormControl мы определяем свойство в контроллере компонента:

    name: FormControl = new FormControl('Alice');

    и привязываем его к конкретному элементу в шаблоне:

    <input type="text" [formControl]="name">

    После чего в контроллере мы можем подписаться на изменения:

    this.name.valueChanges.subscribe(console.log)

    Либо на изменения статуса(валидности):

    this.name.statusChanges.subscribe(console.log)
    Также можно получать статические значения (не подписываясь):
    this.name.value
    this.name.valid
     Полный список свойств можно посмотреть в описании AbstractControl (от которого наследуется FromControl)

    FormGroup

    FormGroup помогает удобно группировать контролы. Например: если мы хотим задавать не просто имя, а полное имя, содержащее само имя и фамилию:

    View the code on Gist.

    и подключаем в шаблоне:

    View the code on Gist.

    Обратите внимание, что для контролов обернутых в formGroup мы уже ставим formControlName свойство (а не [formControl]), которое будет указывать на то, где брать контрол в группе.

    FormArray

    FormArray прекрасно подойдет тогда, когда в форме у вас используется список, в который вы можете добавлять элементы. Давайте сделаем форму “учасников”, которая содержит список участников:

    View the code on Gist.

    и в шаблоне это будет выглядеть так:

    View the code on Gist.

    как видите мы выводим список контролов используя итератор(index) как имя контрола(formControlName) в списке.

    Давайте добавим возможность добавления участников:

    View the code on Gist.

    и для этого в контроллере компонента определим 2 дополнительных метода removeUser и addUser:

    View the code on Gist.

    В итоге получим:

    FormBuilder

    Упростить процесс создания новых форм нам помогает сервис FormBuilder. Который мы можем инжектировать в контроллер:

    View the code on Gist.

    После чего создать туже форму (“учасники”), только теперь с помощью сервиса:

    View the code on Gist.

    вы можете сказать, что кода не стало меньше. Да, это так. FormBuilder имеет смысл использовать только для сложных форм с большим динамическим количеством контролов.

    Валидация данных в реактивном подходе

    Чтобы добавить валидатор на контрол мы всего лишь добавляем второй параметр, который может быть как одним валидатором, так и массивом(применяем разные проверки):

    name: FormControl = new FormControl('Alice', [Validators.required]);

    предварительно импортировав коллекцию валидаторов:

    import { Validators } from “@angular/forms”;

    Мы можем задавать один и больше валидатор. На данный момент в коллекции есть следующие валидаторы:

    • min
    • max
    • required
    • requiredTrue
    • email
    • minLength
    • maxLength
    • pattern

    Создание своих валидаторов

    Валидатор представляет из себя простую функцию, которая возвращает либо объект ошибки либо null:

    View the code on Gist.

    добавляется вторым параметром в контрол( вместе со стандартными валидаторами):

    name: FormControl = new FormControl('Alice', [Validators.required, myNameValidator]);

    В реальных проектах валидаторы собирают в группы заворачивают в классы и делают статическими методами классов.

    Валидаторы с параметрами

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

    View the code on Gist.

    Асинхронные валидаторы

    Асинхронные валидаторы отличаются от синхронных только тем, что возвращают не статические данные, а Observable либо Promise:

    View the code on Gist.

    и также определяются 3-м параметром в конструкторе контрола:

    name: FormControl = new FormControl('Alice', [myNameValidator], [myAsyncNameValidator]);

    Вывод ошибок

    Ошибки контрола хранятся в свойстве errors:

    this.name.errors

    Чтобы сделать какие-то действия в случае появления ошибок, можем написать так: добавив фильтры на изменение состояния и собственно валидность данных:

    View the code on Gist.

    Свойство есть не только у обычного контрола, но так же и у FormGroup, поэтому вы можете получить объект со всеми ошибками формы:

    this.participantsForm.errors

    Создание кастомных контроллов

    Решил вынести эту главу в отдельный пост.

    ]]>
    https://stepansuvorov.com/blog/2017/07/angular-forms-and-validation/feed/ 5
    Запускаем Angular виджет в приложение без Angular https://stepansuvorov.com/blog/2017/06/angular-for-non-angular-apps/ https://stepansuvorov.com/blog/2017/06/angular-for-non-angular-apps/#comments Sun, 25 Jun 2017 16:02:11 +0000 http://stepansuvorov.com/blog/?p=3378 Continue reading ]]>

    Очень маловероятно, что вы захотите добавлять Angular в приложение только для того, чтобы завести один компонент. Рекомендую смотреть на этот пост, не как на практическое руководство к действию, а как на работу по исследованию возможностей фреймворка.

    Предположим что у нас уже есть какой-то компонент, который мы хотим вывести на странице не Angular приложения:

    View the code on Gist.

    Для запуска Angular нам нужно также создать модуль, объявить наш компонент в нем и указать на то, что он будет инициирован динамически:

    View the code on Gist.

    Создав модуль, мы можем его бустрапить:

    View the code on Gist.

    Использование фабрики компонентов

    Чтобы инициировать динамически компонент, нам нужен componentFactoryResolver, который мы можем получить из сущности нашего модуля:

    View the code on Gist.

    теперь можем получить фабрику для нашего конкретного компонента:

    View the code on Gist.

    и с помощью полученной фабрики создать компонент:

    View the code on Gist.

    обратите внимание, что мы произвели создание компонента прям на самом элементе (querySelector(hello)), но это не обязательно, мы бы также могли инициализировать контейнер, который содержит наш hello-элемент (например body).

    Мы вывели компонент на страницу.

    Но еще не все.

    Подключаем механизм обнаружения изменений (Change Detection)

    Чтобы представление нашего компонента реагировало на изменение состояния приложения, нам необходимо добавить hostView компонента в приложение (ApplicationRef). Для этого используем метод attachView:

     ngModuleRef.injector.get(ApplicationRef).attachView(componentRef.hostView);

    Получим:

    View the code on Gist.

    Также мы можем сделать отложенную инициализацию по таймеру (например: через 5 секунд):

    View the code on Gist.

    Вот тут полный пример.

    ]]>
    https://stepansuvorov.com/blog/2017/06/angular-for-non-angular-apps/feed/ 1
    Что нового в Angular 4.2 https://stepansuvorov.com/blog/2017/06/whats-new-in-angular-4-2/ https://stepansuvorov.com/blog/2017/06/whats-new-in-angular-4-2/#comments Sat, 24 Jun 2017 21:14:43 +0000 http://stepansuvorov.com/blog/?p=3373 Continue reading ]]>

    • оператор не нулевого присвоения ( Non-null assertion operator ) теперь можно использовать в шаблонах:

      <h2>{{ user!.name }}</h2>
    • очень много изменений по анимации (смотрите в отдельном посте)
    • добавили поддержку mix & max стандартных валидаторов (но уже в 4.3.0-beta.0 удалили эту возможность признав как breaking change)
    • в тестах появились 3 вспомогательных метода:
      • TestBed.overrideProvider()приближает возможность тестировать в AOT,
      • flush() – для сбрасывания всех счетчиков и выполнения колбэков всех асинхронных операций,
      • fixture.whenRenderingDone() – возвращает промис, который ждет выполнения всех анимаций
    ]]>
    https://stepansuvorov.com/blog/2017/06/whats-new-in-angular-4-2/feed/ 1