Behind The Code Magazine #2

Page 1


About This Magazine Angular conference ngPoland 2018 in a nutshell. Read about our amazing event, meet organizer Dariusz Kalbarczyk, find out about technology from technical articles. We believe that people create technology and that community is a huge part of every conference. This number of "Behind The Code" magazine contains the interviews with the real heroes. Meet Angular authorities from all over the world, who do a lot of really great stuff, are absolutely positive and full of passion. Learn. Inspire. Enjoy! Marta Wiśniewska Angular Developer, BtCM Editor


The biggest Angular Conference in CEE

NgPoland is an amazing event where you can meet Angularians and top speakers from all over the world. The best place to learn about the present and future of Angular and its ecosystem, TypeScript, tools and much more.


Top speakers Every year we are happy to host the best experts in the ied of Angular, TypeScript, RxJS, Redux, etc. Their presentations will let you expand your current knowledge, get practical tips and learn new trends.

Real friendly atmosphere NgPoland 2018 is so much more than being able to learn from Angular authorities. You will also have a great opportunity to get to know and socialize with over 700 like-minded people from all over the world.


Great place Do you like cinemas? Let's prepare for a fantastic movie with real Angular rockstars! Our conference takes place in Multikino cinema ZĹ‚ote Tarasy. It's a unique opportunity to see interesting presentations on such a big screen!



TABLE OF CONTENTS

ARTICLES Read and code

Why People-Performance Numbers are Critical in IT Development

12

Jeppe Hedaa

Be progressive! Make your Angular app progressive (PWA)

30

' ' Marta Wisniewska

At JetBrains code is our passion

44

JetBrains

Providing services in Angular

47

Tomasz Borowski

52

Meet Scalac Scalac

The difference between NgDoCheck and AsyncPipe in OnPush components

57

Max Koretskyi

Ionic Release: v4 Beta 15

70

Mike Hartington

NestJS - Introduction

74

' Kamil Mysliwiec

How `runOutsideAngular` might reduce change detection calls in your app

88

Krzysztof Grzybek BEHIND THE CODE MAGAZINE |

NgPoland 2018

7


TABLE OF CONTENTS

INTERVIEWS

Meet passionate about Angular

Matias Niemelä

10 David Müllerchen

Mashhood Rastgar

15 Mark Pieszak

Minko Gechev

24 26

Martin Sonnenholzer ` Marta Wisniewska

28 35

Alex Okrushko Sherry List

36 38

Ferdinand Malcher Phil Nash

40 42

Aaron J Frost BEHIND THE CODE MAGAZINE

16 20

Manfred Steyer

8

14

|

NgPoland 2018


TABLE OF CONTENTS

Ekaterina Prigara

43 Tomasz Borowski

Michael Hladky

46 50

Dhananjay Kumar Max Koretskyi

54 56

Juan Herrera

66 68

Mike Hartington Vitalii Bobrov Wassim Chegham

77 78

Maye Edwin William Grasel

80 81

Maxim Salnikov Sani Yusuf

82 84

Dmitriy Shekhovtsov 85 Jorge Cano BEHIND THE CODE MAGAZINE

86 |

NgPoland 2018

9


INTERVIEW Matias Niemelä Monster of Animations

Hello my name is Matias Niemelä. I am a Software Engineer working Google on the Angular team in San Francisco, California. During the last 15 years I have been involved in building webapplications left, right and center. I have been apart of anything and everything with to do with web development whether it's design, content creation, dev-ops, backend or front-end development. Currently I'm working on supercharging the capabilities of Angular and it has been an amazing journey so far.

yearofmoo

Why do you love programming? While programming is an engineering skill, it very much consists of many creative elements. And when it comes to web development, there's no other profession that allows for such a rich combination of elements of engineering and design. Whether it be web design, application development or framework engineering, the opportunity push creative boundaries is always there. I love programming because I consistently get to try something new and go after an abstract idea in the hopes to make it concrete. Programmers are lucky because they have a very solid feedback loop system so they almost always know that they are making progress and improving. When you mix together your past experiences with new challenges, the end result will always make you better at what you do. On the Angular team we have a philosophy of stating what you want to achieve and then working backwards. Over the past five years of being involved in the framework, I am happy to say that philosophy has brought a lot of cool new inventions into the framework. 10

BEHIND THE CODE MAGAZINE |

NgPoland 2018


INTERVIEW

Matias Niemelä

Keep sharpening the saw by Matias Niemelä

Did you start your career as a developer? What made you start programming? I started out building websites back in my teens. I was very luck to have many opportunities to prove myself and this helped me refine my skills early on. This lead to me studying Computer Science while also being a freelance web developer at the same time. After building websites for a good ten years, getting involved with opensource then eventually lead me to Angular. So yes I've been a developer all throughout my career and I've very much enjoyed the process so far :) If you had choose a different profession, what would it be? My top choice would've been to become an architect and help design homes and buildings. This profession I feel would also contain elements of creativity, but would rely on science, engineering and the realistic elements of nature.

What do you think about getting involved with the community? Being involved with Angular has been a rewarding experience since day one. The community is very open, friendly and inspiring and there's always room for more people and for fresh new ideas. Everyone is very humble and there's so much out there.

Which latest feature/features of Angular is/are the best because of developer experience? The latest feature that I believe will really set the bar for Angular is the Angular Ivy Refactor when mixed together with Angular Elements. The refactor is a re-envisioning of the rendering architecture will allow for Angular to be operate with a lot more flexibility (which is essential for the landscape of the web). Once Ivy is in place, smaller-sized Angular applications be much more lightweight and will be able to operate more effectively alongside CustomElements (which is what Angular Elements is all about). This means that widgets ranging from simple to complex can be written and packaged in Angular and used in websites that are not Angular-focussed. Also the new styling capabilities of Angular Ivy are pretty darn stylish.

What do you do in your free time? I very much enjoy anything design-oriented, traveling to new places and partaking in just about any sport I can get involved with.

NgPoland 2018

|

BEHIND THE CODE MAGAZINE

11


ARTICLE Why People-Performance Numbers are Critical in IT Development by Jeppe Hedaa

I love people, and I truly believe that every individual is amazing and valuable, but that doesn’t mean that everyone is the perfect IT enterprise architect or project manager. It is really important to find the perfect match to optimize your IT organization’s performance. Since "Nucleon was published, one of the things that frequently comes up in conversation is the idea of putting a number on people in order to find the top performers, or the “10s.” I believe we must put a number on every individual’s performance in the IT organization. Why? Because the individuals in an IT organization are by far the most performancegenerating factor in complex systems development. (“People make a difference” was my company’s slogan from 1998 to 2008 — at 7N we stopped using it only because everybody else was using it by then.) I have seen case after case where individuals have impressed me in a way no tools, system or methodology could ever deliver on. Tools and methodologies are of no use without a human component and interaction, yet we continue to analyze performance, price, and “user friendliness” more often than we analyze people. We need to evaluate our greatest resource, and assigning a number to performance is the way to do it. I can understand people having some reluctance about this — no one likes to be thought of as a number. However, this is what we do as a society, starting from young ages with personality profiles and educational testing scores. Every individual under 25 is accustomed to being evaluated every day in the school and university environment. That being the case, why is it that when we grow up we are reluctant to evaluate ourselves or have our peers evaluate us in a similar way? Is it too confrontational? Is it too uncomfortable?

12

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


ARTICLE

Jeppe Hedaa

We are talking about the most important factor in IT delivery. We have to be as objective and honest as possible in identifying the performance of our team members: otherwise, how can we develop as professionals and individuals? Though making a practice of assigning numbers on a gut-feeling level is better than not reflecting on individual performance levels at all, in Nucleon I introduce a more objective way of assessing people — one that uses standardized measures, processes and tests to provide a better understanding of what an individual can deliver and what job function is the best match. You can assess individuals in hundreds of ways, and I strongly believe you should find one that fits your own culture. At 7N we have always assessed people by assigning a numerical category from 1 to 10: the lowest-level performers are a 1 and the top performers are 10s. My research in performance revealed that 10s, who are the top 1% of all IT professionals in a normal statistical distribution, perform at a level that is almost two times greater than that of the next level’s performers who we call 9s and who typically represent the top 3% of a population. Going further down the line, 10s perform at a level that is twenty times greater than that of an average IT specialist level of performance. 10s are at a level that is one hundred times greater than that of individuals classified as 1s.

That’s the basis for Nucleon: let us derive realistic numbers so that it becomes clear when things have gone badly or if your people are performing brilliantly. That’s why we need tools and methodologies to assist us in getting a realistic and valuable picture of our collective performance level. People are the core of anything you want to do in IT. You need to identify the individuals who have a realistic chance of delivering high performance, and you need to match them perfectly to the jobs they are best suited for. Focusing on identifying the best people and attracting them for the right position will guarantee you enormous success in your development efforts, project after project. I promise you.

NgPoland 2018

|

BEHIND THE CODE MAGAZINE

13


INTERVIEW David MĂźllerchen Webdave

const community = 'Rocks'; by David MĂźllerchen

webdave_de Can you introduce yourself? Like who are you and what do you do?

I started my career as a electronics technician. After I switched to a company which produced Tablet Computers as a production foreman, I was looking to connect to the production line (pick and place, soldering, AOI) to improve the productivity. I found JavaScript and found my love.

I'm an Angular consultant and trainer. My passion: sharing knowledge. I love to speak and teach at meetups and conferences. I'm also an organizer of the Hamburg AngularJS Meetup and a GDE in Angular. Get in touch with me on Twitter @webdave_de

What do you think about getting involved with the community?

Which latest feature of Angular is the best because of developer experience?

It's important. You get in touch with awesome people, learn so much, can ask questions. It's the most important part of my developer life.

Angular CLI prompt

Why do you love programming?

What do you do in your free time?

I love to create things.

14

BEHIND THE CODE MAGAZINE

Did you start your career as a developer? What made you start programming?

Spend time with my family, camping, diy projects

|

NgPoland 2018


INTERVIEW Mashhood Rastgar CTO @ Sastaticket

while(technology.new === available) { technology.learn() } by Mashhood Rastgar

Can you introduce yourself? Like who are you and what do you do? I lead the Engineering team at a startup and am the GDE for web and Angular! I love working on amazing products and helping other people help build them. Why do you love programming? Its something I feel natural at, i like problem solving on my computer

mashhoodr

Did you start your career as a developer? What made you start programming?

What do you think about getting involved with the community?

Yes, I started when I was just 12 years. I sold my ďŹ rst website at 17.

Which latest feature of Angular is the best because of developer experience?

What do you do in your free time?

Angular CLI prompts are pretty amazing, and make life easier when building your apps

NgPoland 2018

I have learnt a lot from different people over the years, so I think its only fair to give some back!

Read and learn about new technology!

|

BEHIND THE CODE MAGAZINE

15


INTERVIEW Mark Pieszak Founder of DevHelp.Online

Cześć! I'm Mark Pieszak, developer, founder, open-source maintainer/contributor, and currently located in South Florida. I'm the Founder of DevHelp.Online which has started a few years back, and since then we've grown so much! We're a consulting & training firm focused primarily on JavaScript based applications, NodeJS & ASP.NET. MarkPieszak We've been working with some amazing enterprise clients to help them elevate their teams/applications and take them to the next level - whether that's through extra help pushing a project forward, application architecture guidance, trainings, and workshops. Being a software consulting company, our mission has never been to just "get things done" - but to help bring everyone to a level of knowledge where they feel comfortable to tackle it themselves afterward. I've also been part of the Angular Universal team since Angular alpha. I have made so many incredible friends & learned so much in the process! I also have a huge passion for and contribute to NodeJS, ASP.NET and many other projects as well. I absolutely love open-source and the community around it.

16

BEHIND THE CODE MAGAZINE |

NgPoland 2018


INTERVIEW

Mark Pieszak

rm -rf node_modules && npm install by Mark Pieszak

Did you start your career as a developer? What made you start programming? I was fascinated by computers when I got my ďŹ rst one back in 1994 (133mhz computer, yikes) and I dreamed of being a game developer. Years later, I actually started making websites for fun in the late 90s, <table style="no-css: true"> woo, and realized maybe my passion lies elsewhere? In 2002, I went to a university in Philadelphia for Computer Science where I realized that all of the exciting stuff was happening -outside- of what was being taught in the classroom, and although it's important to learn the languages and techniques of the past; I was more curious about what was currently happening in the tech world. So I started teaching myself more and more about the Web, and I was completely fascinated by JavaScript - which at the time, was completely shunned and hated by everyone, and mainly used for swapping images. I had a feeling there was untapped potential here that was missing, and from then on - I had to know everything about JS and browsers. Somehow in the crazy world of ever changing fads, browser incompatibilities, and wild DOM problems - I realized that Web development was -it- for me. Why do you love programming? I just love the challenge of it all. It's ever-changing, and although it can drive you absolutely nuts... programming is always interesting - and right before things get dull, the development community comes up with a new paradigm, and all of a sudden you realize there's a better way of doing so many things you've been doing for years! At the end of the day, we're all trying to ďŹ nd better ways of doing the same things and I think that's what makes the developer community so strong.

NgPoland 2018

|

BEHIND THE CODE MAGAZINE

17


INTERVIEW Mark Pieszak

What do you think about getting involved with the community? As someone who's been part of the community for a few years now, I wish I had joined it a LONG time before I really did! I had created a lot of tools long ago, but at the time I had no idea that open sourcing them was an option. It's one of those things that you don't realize how much you're missing out on until you experience how amazing it is to be a part of something so great, with many brilliant and inspiring people. I thank a lot of my career to the many friends I've made along the way - there are too many people to list here - but you know who you are!

What do you think, which latest feature of Angular is the best because of developer experience? Well TypeScript isn't specific to Angular - but the Angular team really brought it to light when they decided to drop AtScript and use TypeScript. Now all the frameworks allow you to write in it, and it's really picked up full steam. The confidence that TypeScript gives you (even if types aren't -perfect-), is just phenomenal. I mean I've been writing Node with it for years now (better yet - with NestJS), I can't imagine coding without it now :) Angular-wise, I'd say that Angular Elements will be the biggest game changer. If you've been following along to other JS Communities, all the frameworks are basically boiling down to being "Compilers" that output some sort of optimized code - and I see Web Components (when they are 100% supported), being the perfect version of that output. (Once all the kinks are figured out). If that isn't the final result, then at least having the ability to use Angular Components inside of non-angular applications (legacy apps, etc), will be a big win for the community!

What do you do in your free time? Traveling with my wife, playing the guitar, running around with my crazy golden-doodle, and trying to find more free time to finally beat Zelda...

18

BEHIND THE CODE MAGAZINE

|

NgPoland 2018



INTERVIEW Minko Gechev Developer Programs Engineer in the Angular team at Google

mgechev

I’m originally from Troyan, Bulgaria where I spent my childhood. For college, I moved to Sofia, Bulgaria where I graduated BSc and MSc in Software Engineering from Sofia University. In Sofia, I also took a few engineering roles before I became a freelance consultant. Few years after that, I moved to Silicon Valley where I joined the venture capital fund Learn Capital, where I was doing technical consultancy for different portfolio companies. In Learn Capital, I had the chance to meet a lot of brilliant people and learn a lot. Together with few of them, we founded Rhyme.com a startup focused on online learning.

During all these years, since I moved to Sofia, I was actively working on open source projects and giving a lot of talks about JavaScript, Angular, software engineering, and computer science. Some of my projects got popular and awarded by Google and the President of Bulgaria. That’s how I discovered that my real passion is building tools for developers. Reflecting on this, I decided to leave Rhyme.com and pursue a new career path as an engineer in the Angular team at Google. Why do you love programming? I’d say I love programming because of two main reasons: - It allows me to solve real-life problems with a minimum amount of resources - Programming is the most accessible way to apply bleeding edge scientific ideas and make an impact within hours All you need to solve a real-life problem with programming is a computer. From there on, it’s up to you to make an impact with a high-quality system! Programming also has a rock-solid theoretical foundation. I know maths doesn’t sound very attractive because of the way we’ve studied it in school, but it contains the most truthful and concentrated knowledge about the world that we have. It’s fascinating how programming blends a variety of different concepts described in various branches of mathematics. 20

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


INTERVIEW Minko Gechev

while (true) explore(); by Minko Gechev

Did you start your career as a developer? What made you start programming? In high-school, I was very interested in astrophysics and software engineering. Back then, it wasn’t an easy choice which path to take because I was very passionate about astronomy. I used to spend a lot of sleepless nights observing the stars with my telescope and do various calculations and reports. In the same time, I was participating in school software engineering competitions where I had to develop a system and present it in front of an audience. Later, a jury of experts had to evaluate the work of all participants and pick the laureates. When I had the requirements for the system in my head, I was getting obsessed until I had it up and running. I remember spending tens of hours writing code for my projects. Later, having the functioning system, I was feeling so proud of myself! I still experience the same rush of dopamine when I complete a challenging project. What do you think, which latest feature/features of Angular is/are the best because of developer experience? There are a variety of features in the entire Angular ecosystem which provides excellent developer experience. Since the beginning Angular was built with tooling in mind. The Angular’s templates are statically analyzable, the routing as well. This allows third-party developers to provide amazing tools just by statically looking at the source code. Few examples are Compodoc, codelyzer, and Guess.js. Thanks to the declarative routing declaration in Angular, I was able to provide seamless, generic support for predictive prefetching of JavaScript bundles by using a pluggable prediction model. The Angular CLI is also very powerful. Thanks to schematics, it provides the most flexible pipeline out there. In the CLI team, we’re working very hard on making the build well encapsulated so that developers can focus on what’s important - their application, and let the CLI take care of the rest. Looking at Material, it grew so much over the past a couple of years! The CDK (Component Development Kit) continually expands with a variety of useful abstractions which help developers have great experience in creating applications.

NgPoland 2018

|

BEHIND THE CODE MAGAZINE

21


Minko Gechev INTERVIEW

What do you think about getting involved with the community? I think getting involved with the community has a lot of benefits on a lot of different fronts! There are different ways someone can contribute: -

Working on open source projects Writing content on topics they are experienced in Organizing community events Providing mentorship Much more!

I started with the three points above because they are the closest to me. Working on open source projects is probably the best thing that a software engineer, a technical writer, or a designer can contribute with. An open source project contains knowledge with a very high concentration. For example, reading and contributing to the source code of AngularJS, and later Angular, I learned a lot about design patterns, algorithms, self-adjusting computations, and much more! On top of that, by contributing to an open source project, you have the chance to work with some of the best software engineers in the world - for example, the chances are that Miško Hevery would review your pull request if you contribute to Angular. If you are passionate about programming languages - Go is a great start. On the Go language are working awardwinning engineers who have developed Unix. It doesn’t matter where are you in the world, as soon as you have a computer, internet connection, and you’re willing to learn - you can work with the best. Sharing content in an area where you have an expertise in is also a great way to get involved with the community. Millions of developers are constantly googling problems they face on a daily basis. If you face a challenge at work and you find an elegant solution, write an article about it - that’s the perfect content for a blog post. Just share it and give back to the community! Organizing community events is another way to get involved. If in your hometown there are engineers with similar interests but there’s no place for them to hangout - ask your company if they’d want to host a meetup and buy pizza! This is an enriching experience - helping likeminded people to collaborate, meet, and exchange ideas. What do you do in your free time? In my spare time, I enjoy doing sports, mostly boxing and karate, reading theoretical computer science, exploring San Francisco, and traveling the world! When traveling for a conference, I always try to stay a day or two longer so I can feel the vibes of the place I’m at.

22

BEHIND THE CODE MAGAZINE

|

NgPoland 2018



INTERVIEW Manfred Stayer Architect, Trainer & Consultant Can you introduce yourself? Like who are you and what do you do?

ManfredSteyer

I’m an architect, trainer and consultant with focus on Angular. I’m writing web-based business software since the late 90s. Back then, I was a technical team lead. At the same time I’ve studied IT and Marketing part-time at the week ends and then I began to tech software engineering at an university of applied sciences. I did this parttime as a free-lance teacher and some years full time. After quitting my job in the area of web development, I’ve started to help companies with trainings and consultancy in that area.

Why do you love programming? The nice thing about programming is, you can build something exciting that helps people. And I’m also interested into programming techniques, patterns and frameworks. Did you start your career as a developer? What made you start programming? My parents send me to business school. I did not enjoy it at all. Instead of learning for school, I’ve concentrated on learning programming. I’ve read a lot books and tried everything out. Also, I did some internships regarding database and web development and so my first real job was about this.

24

BEHIND THE CODE MAGAZINE |

NgPoland 2018


INTERVIEW

Manf red Stayer

while (day.isNotOver) doSomethingMeaningful(day); // Carpe diem by Manfred Stayer

What do you think about getting involved with the community? Currently, I’m part of the Angular community and I really like it. It’s really open and friendly. It’s also a good feeling to give something back to the community when doing open source or blogging. And it’s great to get quick feedback.

Which latest feature of Angular is the best because of developer experience? I really like tree shakable providers as they give a foretaste of a world, where modules are optional.

What do you do in your free time? Family, Friends, Cinema, Star Trek and Batman ;-)

BEHIND THE CODE MAGAZINE

|

NgPoland 2018

25


INTERVIEW MartinSonnenholzer Principal product engineer at SinnerSchrader

Can you introduce yourself? Like who are you and what do you do? I am a cat person. That's why you can ďŹ nd a grumpy looking cat as my avatar almost everywhere. I also love math and since my university time I like to play around with everything in regards to machine learning, not only the neural networks stuff ;). But I worked most of my professional career as a backend and frontend developer. My day to day job is Angular, what I am developing since version 1.0.7. chaos_monster

Why do you love programming? Coding is my possibility to express my creativity. When you program the only the limit is your imagination. Whenever you see a problem you can ďŹ nd a solution. This fascinates me since I was a kid and played around with basic on my C64.

Did you start your career as a developer? What made you start programming? I actually wanted to become a teacher, but as life goes I switched to become a programmer. But my start was way earlier, I just didn't see it as a profession.

26

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


INTERVIEW Martin Sonnenholzer

import { solution } from "unexpected-places" by Martin Sonnenholzer

What do you think about getting involved with the community? I started to go on meetups and I loved to meet new people and get new input everytime. After a while I co-organized the Angular meetup in Berlin and now I don't want to miss the community anymore, because it gave me so much positivity <3 in my life. And I hope to give back as much as I can.

What do you do in your free time? My profession is oating so I also like to learn more and new stuff when I am at home. But it must be in balance so I like to spent time with friends and my girlfriend.

NgPoland 2018

| BEHIND THE CODE MAGAZINE

27


INTERVIEW ' Marta Wisniewska Front-end Developer at Cosmose, PWA enthusiast

if (you.optimism) happiness.find(1); by Marta Wiśniewska

Can you introduce yourself? Like who are you and what do you do? I'm an Angular Developer and passionate about web development, PWA and hybrid apps. I am a co-author of PWA Fire ( pwafire.org ) - an open source project that allows you to build the progressive web apps. I'm also a member of GDG Warsaw. I love to participate in conferences, meetups and all the events where you can meet amazing people and share your knowledge. Why do you love programming? Well, programming allows you to create anything you want. All you need is code. This is a kind of abstract thinking in which everything is logical, structured, each line of code makes sense, and the whole creates something super awesome. That's why I love IT :)

MartaW_PL

Did you start your career as a developer? What made you start programming? When I was at high school someone told me that programming is so difficult. I tried to find studies where there was no need to code and I started the Power Engineering studies. But fortunately, I had Computer Science in my first semester. Then I spent a lot of time learning C programming language and I loved it <3. I've decided to take a second major field - Computer Science. In my Bachelor thesis, I mixed Power Engineering and Computer Science and I developed a web app for a wind farm. That was my last adventure with Power Engineering. Now, I'm a regular Front-end Developer :) 28

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


INTERVIEW Marta Wiśniewska

What do you think about getting involved with the community? Work with the community is wonderful! You meet amazing people and learn a lot. It make you motivated, inspired and truly happy.

Which latest feature of Angular is the best because of developer experience? I really like schematics. It's a nice tool to automate developer's work. Your one line in CLI has never been such powerful before Angular 6 :)

What do you do in your free time? I love running, gym, dancing and travelling <3

NgPoland 2018

| BEHIND THE CODE MAGAZINE

29


ARTICLE Be progressive! Make your Angular app progressive (PWA) by Marta Wiśniewska

2018 is called the year of Progressive Web Apps. is technology signi cantly boosted in the last few years. Currently is one of the main goals for e-commerce investments. From the developer side, it's just a way to empower applications to deliver a user experience with the reliability and performance on par with natively-installed code. In this article, I will show you how to apply PWA features to your Angular application.

Progressive Web Apps are the next step in web development evolution. This technology evaluated because of users' needs. Today we are focused on mobile. Responsive web design (RWD) is still an essential requirement for web applications. The current state of the web is going forward. "Mobile first" strategy transforms into a more advanced approach to get native look and feel. PWA give us the same user experience advantages as native apps, but we still use web standards and interfaces, that are well-known and easy to use.

PWA The what?

What does create an excellent user experience (UX)?

Progressive web apps (PWA) use modern web APIs along with traditional progressive enhancement strategy to create cross-platform web applications. These apps work everywhere and provide several features that give them the same user experience advantages as native apps.

Three main features of PWA makes a fantastic UX. Progressive Web Applications are fast, reliable and engaging. These apps work regardless of network conditions. What's important and new for web development - can work offline and in unstable net connection.

source: MDN web docs 30

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


ARTICLE Marta Wiśniewska

Web alternative for native apps? Progressive web applications are still web apps but better. The most significant differences between a regular (responsive) web application and a native app are access to the device (access to the native features) and the possibilit to engage users. These advantages are possible to use in progressive web apps. This technology compares the best of web and the best of native apps.

A web developer can implement functionalities that are typical for the mobile devices (camera, geolocation, push notifications, background synchronization, etc.). PWA don't require installation but look like native apps, and can be launched from a homescreen. This feature compared with push notifications allow you to increase user engagement. That's a reason why PWA technology is a growing trend in e-commerce.

Success

stories

Know-how! PWA implementation If you want to develop PWA, you should know three basics requirements for a web app: using a service worker, adding a web manifest, serving an app over HTTPS. That's fundamentals for PWA. Let's take a closer to these standards. Service worker is a kind of web worker, that can work independently from your app and can control it (even in offline state and also when a user leaves a page). Service worker functions as a proxy and manages caching for an application. Particularly, this is a javascript file, registers in the web browser during the first app run. Service workers are restricted to running across HTTPS for security reasons. The web manifest is an app description in JSON format. This file is attached to the HTML code of your app. If your app has added a manifest, you can run it from a home screen. source: pwastats.com

NgPoland 2018

| BEHIND THE CODE MAGAZINE

31


ARTICLE

Marta Wiśniewska

Angular's Service Worker Every web app can be progressively enhance. It doesn't matter framework you use. The matter concerns implementation of service worker. You can do it manually - write your own code or use automated solution - Angular's Service Worker (NGSW). Angular's service worker is designed to optimize the end user experience of using an application over a slow or unreliable network connection, while also minimizing the risks of serving outdated content. Let's focus on the Angular's Service Worker behavior follows that design goal: -Caching an application is like installing a native application. The application is cached as one unit, and all files update together. -A running application continues to run with the same version of all files. It does not suddenly start receiving cached files from a newer version, which are likely incompatible. -When users refresh the application, they see the latest fully cached version. New tabs load the latest cached code. -Updates happen in the background, relatively quickly after changes are published. The previous version of the application is served until an update is installed and ready. -The service worker conserves bandwidth when possible. Resources are only downloaded if they've changed.

Codelab: PWA & Angular Ready, set, code... We need Angular CLI v6+ version. Let's check it: ng --version

If your Angular CLI version is lower than 6, install the newest version: npm install @angular/cli

Now we can create new Angular project: ng new pwa

It's time to add service worker and make our app progressive. Let's go to the new directory with our Angular project. cd pwa

Now I use my favorite (because of DX) Angular feature - a Schematic. I add a service worker and needed packages using the only one command: ng add @angular/pwa

Let's analyze what happened inside Angular project: git status

32

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


ARTICLE Marta Wiśniewska

On branch master Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: modified: modified: modified:

angular.json package.json src/app/app.module.ts src/index.html

Untracked files: (use "git add <file>..." to include in what will be committed) ngsw-config.json src/assets/icons/ src/manifest.json As you can see, there are three untracked files inside the project: ngsw-config.json

instruction for the Angular CLI how to handle assets for caching

icons

directory for icons in various sizes

manifest.json

describes your app in JSON format and makes it installable

There are also changes to the existing files. angular.json

manifest.json added to the assets, service worker set "service-worker: true"

package.json

new dependencies added: @angular/service-worker and @angular/pwa

app.module.ts

a new ServiceWorkerModule that's imported and is being told to register a service worker if the app is being built for production.

index.html

manifest.json added to the head tag, a theme-color set

NgPoland 2018

|

BEHIND THE CODE MAGAZINE

33


ARTICLE Marta Wiśniewska

Running A service worker only get's registered if we build the app in production mode. Angular CLI's server however doesn't support service workers with --prod, so we'll have to use a different server. There are a few solutions. W can install lite-server (using npm) and run it. As you read before about PWA basic requirements, PWA should be served over HTTPS. For me, the easiest way to do this is to use Firebase Hosting function. Install dependencies for Firebase: npm install firebase-tool Log in to the Firebase locally: firebase login Init a firebase project. Set proper project name, function: hosting and directory with bundle created during the building process: firebase init Build your app and then deploy: firebase deploy After successful deploy, you get an URL. Open it in a browser. Don't forget test that SW is registered and your app works Offline.

Testing To test PWA use Lighthouse tool. Open tab Audits in Chrome Browser, select option Progressive Web Application, run Audit test and make your app 100% progressive.

More PWA? If you want to know more about Progressive Web Apps visit our opensource project PWA Fire (pwafire.org) and follow us on Twitter @pwafire 34

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


INTERVIEW Alex Okrushko Software Engineer at Google, Firebase new Promise((resolve, reject) => you.love(you.do()) ? resolve( theRest()) : reject(keepLooking())); by Alex Okrushko

Hey, I'm Alex. Currently working on Firebase Console web app, mostly focusing on general app infrastructure as well as ML Kit, so that our users (who are developers like you) can unleash the powers of Machine Learning in their apps. I'm also maintaining NgRx at Google and leading its usage in Firebase. Why do you love programming? I like building things in general and solving interesting problems in particular. Something about creativity and persistence that go in the process of writing code gives me a lot of pleasure. I can barely notice how the day ies by when I start working in the mornings.

Did you start your career as a developer? What made you start programming?

What do you think about getting involved with the community?

I started programming at school, but when I got into university, I stopped and was focusing on other things. Later on, I decided to come back; however I got into Test Automation at ďŹ rst, where I spent almost 5 years.

I love to be involved with the community! For the past year, I was trying to be more engaged: wrote an article at blog.angularindepth.com, open sourced a few helpful RxJS operators, participated at numerous Angular conferences and gave a few workshops.

Which latest feature of Angular is the best because of developer experience? love tree-shakeable providers (and injection tokens)! They are invaluable: improve ergonomics of the NgModules, streamline the providing mechanisms, make it easier to write unit tests (less mocking), reduce the sizes of the apps and so on :) I also like what Angular Material team is doing with CDK - those are amazing tools to build upon. NgPoland 2018

AlexOkrushko

|

What do you do in your free time? I try to spend time with my family - I have 3 little kids under the age of 5, so that means I'm always busy :) Also, I enjoy woodworking an playing basketball.

BEHIND THE CODE MAGAZINE

35


INTERVIEW SherryList ngVikings co-organizer

while (!death) { have_and_hod(); love_and_cherish();} by Sherry List

Did you start your career as a developer? What made you start programming?

Can you introduce yourself? Like who are you and what do you do? I work as front-end lead developer at Nordea bank in beautiful city of Copenhagen. Next to my daily job, I organize ngCopenhagen and GDG Copenhagen meetups. I’m also one of organizers of ngVikings conference, which is the only travelling Angular conference in the world. Recently I also started to give talks at conferences mostly with a very good friend of mine Ana Cidre. Ah I forgot to mention that I am also Women Techmaker Lead of Copenhagen.

36

BEHIND THE CODE MAGAZINE

Yes. When I was around 13, I was 100% sure that I wanted to become a Software Engineer. Therefore I decided to go to a technical high school. After finishing high school, I was lucky to have an older cousin who is an entrepreneur. He offered me a position at his company as web designer. It was the best thing that happened to me. At his company, I managed to work with really amazing developers and engineers who really shaped my mentality to become a self learner. Instead of teaching me from A-Z they gave me assignments and resources where I could surf and learn how to find my answers. |

NgPoland 2018


INTERVIEW Sherry List

Which latest feature of Angular is the best because of developer experience?

Why do you love programming? Well I always loved to solve problems and of course the feeling you get afterwards once its solved.

What do you think about getting involved with the community? Well, first of all it helps to grow your network. You get to know a lot of passionate people with the same interest. It gives you possibility to find not only new friends but also potential future jobs.

It's difficult to choose, but if I have only one option, I choose CLI. CLI helps new developers to just focus on learning Angular and no need to sped time on configuring the build system and everything around that.

sherrrylst

What do you do in your free time? Apart from all my community activities, I love to spend time and travel with my husband, Troels and our little dog, Lance.

NgPoland 2018

|

BEHIND THE CODE MAGAZINE

37


INTERVIEW Ferdinand Malcher Co-founder and trainer at Angular.Schule

I'm Ferdinand and currently working as a freelancer doing "everything web and fun". I'm based in Leipzig, Germany (in fact, one of the most beautiful cities in Germany). While open for the web in general, my greatest passion in fact is Angular. In 2017 we published a printed German book about Angular – now I do mostly training, consulting, blogging and conference speaking about Angular. fmalcher01 Why do you love programming? I love programming because it abstracts things from the real world. You can so easily connect it with everything you already know, and let computers support humans in what they do, be it hobby or business. What is more, it is so much fun and even as a beginner you can get fast success for easy problems, that's so cool. Did you start your career as a developer? What made you start programming? Actually, the web fascinated me from the first day I used a computer. When I was 10 I had the big dream to get an own website. I got one, it was really ugly but I called it the second-best home page in the world", haha. I always loved the web and never stopped exploring things. In 2014 I did my first AngularJS side-project and it was love at first sight (sorry jQuery) 38

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


INTERVIEW

Ferdinand Malcher

days$.pipe( map(day => day.bad ? day.applyHappiness() : day) concatMap(() => sleep(8)), ).subscribe(day => { laugh(); angular(); goOutside(); }) by Ferdinand Malcher

What do you think about getting involved with the community? Actually, the Angular community is one of the friendliest, most inclusive, most diverse and open-minded I've ever met. Even if you don't know people yet, you are welcome everywhere, because there's that strong mutual interest between all of you. I love Angular conferences and even been at the ng-conf in Salt lake City as an attendee three times, just because it feels so good and always creates a little ame in my heart ;-)

What do you think, which latest feature of Angular is the best because of developer experience? Tough question! Developer experience is one of the main reasons for why I'm so passionate about Angular. When I need to pick one, that'd probably be Schematics. Remember the time when you needed to set up NgRx, PWA, Universal and Material by hand? Opening the CLI interface to everyone was a very good decision. Another thing is that Angular is so opinionated: For most topics there is one golden way of doing it. That makes it far easier for new developers to recognize and apply the patterns and techniques they know.

What do you do in your free time? I spend a lot of time at my computer. However, I'm very passionate about photography and hiking (those two can be connected very well!) and I love singing and playing the piano, even though I couldn't ďŹ nd much time for this in the last months...

NgPoland 2018

| BEHIND THE CODE MAGAZINE

39


INTERVIEW Phil Nash Developer evangelist

Hi! I'm Phil Nash and I am a developer evangelist for Twilio. I'm originally from the UK and I've now been living in Australia for a year.

philnash

Why do you love programming? I love programming because I love that typing a few commands can create so many different things. It's a mixture of problem solving and creativity and it's backed by a huge community of people who are willing to share or help.

Did you start your career as a developer? What made you start programming? I was lucky enough that my school included some programming as part of the curriculum, I wrote my ďŹ rst HTML at the age of 13 (back when <FONT> tags were still a thing) and that turned out to be my hook. I took maths and computer science at university, but that almost put me off development, until I found myself building websites for myself and my friends and decided that a career in web development was the way forward. The rest is history.

40

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


INTERVIEW

Phil Nash

valueOf(you) < valueOf([you, ...community]); by Phil Nash

What do you think about getting involved with the community? Getting involved with the developer community is one of the things that will always make programming even more fun and always different. The community is a support network, a sounding board for ideas and a constant source of inspiration. I've been lucky enough to meet incredible people all over the world just through a shared love of programming and I recommend getting involved in any way you can.

What do you think, which latest feature of Angular is the best because of developer experience? I love that the Angular team are focused on developer experience and the recent updates to the CLI show that, making it easier to upgrade, easier to start projects and easier to make changes as you grow your app. I also really like how Angular Elements is coming along; to truly succeed on the web you must always bet on the platform and it's about time for web components to step into the light. Angular support for that is good for the web and good for the Angular community.

What do you do in your free time? I love live music, exploring Melbourne, seeking out new craft beers to taste and hanging out with my girlďŹ rend and my dog. And sometimes I can't help but spend a bit more time programming in my spare time too.

BEHIND THE CODE MAGAZINE |

NgPoland 2018

41


INTERVIEW Aaron J Frost CEO HeroDevs if(opportunities.length && mustTakeStepBack) takeStepBack().then(takeOpportunities); by Aron Frost

I'm Aaron, or Frosty. Whichever you'd like. I'm one of the co-founders of ng-conf, the world's original Angular conference. I'm also the CEO of HeroDevs, a team of elite web developers who write enterprise code for companies of all types. Additionally, i'm a father to 5 mini-frosties and love to spend my free time outdoors. Why do you love programming? Programming gives me the opportunity to chronically solve problems. As soon as you fix one, there's more. My brain loves living each day with constant challenges.

Did you start your career as a developer? What made you start programming?

aaronfrost What do you think about getting involved with the community?

I started in QA, one I realized I had some skills with SQL. Then I moved to programming over time. After progressing to Sr QA, it took time to make the climb to full time developer.

Getting involved in the community is what sets experts apart from other engineers. Taking the time to help others in the same ways that you have been helped is what makes communities happen.

Which latest feature of Angular is the best because of developer experience?

What do you do in your free time?

Schematics is great because they make hard things trivial. They enable one Angular engineer to provide benefits for thousands of others.

I have a wife and five children, and two businesses. I don't know what the words "free time" mean.

ReactiveForms aren't new, but they bring sanity to creating forms in Angular. 42

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


INTERVIEW Ekaterina Prigara Product Marketing Manager at JetBrains

if (friends && goodNightSleep) {console.log("‫})" ؁‬ by Ekaterina Prigara

Can you introduce yourself? Like who are you and what do you do? For the past 5 years, I’ve been working as a Product Marketing Manager for the WebStorm IDE at JetBrains. Together with the product development team, we are working to build the best IDE for web (and Angular!) developers. I also create a lot of educational content about using the IDE and different frameworks and tools in it. Did you start your career as a developer? What made you start programming? When I was still in high school, the Web 2.0 boom started. It got me very much interested in web development and I decided to study software engineering at the university. After graduating, I worked as a front-end developer before switching to product management.

Which latest feature of Angular is the best because of developer experience?

As a person working on a developer tool, I’m most excited about the new features in the Angular CLI: Angular schematics and ng add.

NgPoland 2018

|

katyaprigara Why do you love programming? What I love the most is how easy it is to build something interesting and useful (compared to making a physical product). I like how languages and technologies evolve, thanks to the communities around them and make it possible to build new products faster and easier. What do you do in your free time? I cook and bake a lot on weekends and love long bike rides.

BEHIND THE CODE MAGAZINE

43


ARTICLE

At JetBrains, code is our passion For over 15 years we have strived to make the strongest, most effective developer tools on earth. By automating routine checks and corrections, our tools speed up production, freeing developers to grow, discover and create.

The drive to develop We make professional software development a more productive and enjoyable experience. We help developers work faster by automating common, repetitive tasks to enable them to stay focused on code design and the big picture. We provide tools to explore and familiarize with code bases faster. Our products make it easy for you to take care of quality during all stages of development and spend less time on maintenance tasks.

44

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


ARTICLE JetBrains

JetBrains maintains its headquarters in Prague, Czech Republic, with its Research & Development labs located in St. Petersburg, Moscow, Novosibirsk, Munich and Boston. The company, initially called IntelliJ Software, was founded in 2000 by three seasoned software engineers. Now it employs close to 800 people all around the world.

Whichever technologies you use, there's a JetBrains tool to match Our products include the top-notch IDEs for Java (IntelliJ IDEA), JavaScript (WebStorm), PHP (PhpStorm), .NET (ReSharper and Rider) and other languages and a range of team tools (TeamCity, Upsource, and YouTrack). We are also the creators of Koltin, the programming language targeting the JVM and JavaScript, which became the official language for Android in 2017.

Webstorm The smartest JavaScript IDE WebStorm is our IDE for JavaScript developers. It has a first-class support for React, Angular and Vue, smart code completion and refactorings, a built-in debugger for the client-side JavaScript and Node.js, and lots of integrated tools. As all other IDEs by JetBrains, WebStorm is built on top of the open-source IntelliJ platform, so it inherits a rich plugin ecosystem from it.

NgPoland 2018

| BEHIND THE CODE MAGAZINE

45


INTERVIEW Tomasz Borowski Senior Frontend Developer / Angular Trainer

try { doWhatYouLove() } catch(e) { doWhatYouLoveAnyway() } by Tomasz Borowski

Can you introduce yourself? Like who are you and what do you do? My name is Tomasz Borowski and I'm frontend developer who develops web apps at Jcommerce and teaches Angular by building space ships* at Angular in Space workshops. * well, those space ships fly just in browser... for now ;) What do you think about getting involved with the community?

Why do you love programming? I enjoy creating things out of nothing. Sometimes it just starts from a simple idea, then it changes into a plan and finishes with the implementation. Overcoming the problems that happen on the way is also very rewarding.

Without communities we would not have such a great open-source projects like Angular. They are essential for any developer, hence everyone should feel encouraged to contribute.

Did you start your career as a developer? What made you start programming? Yes, I started my career as a developer about 10 years ago by making a dozen of simple websites with PHP. Then, for about 5 years, I was coding in Ruby on Rails and finally I ended up with JavaScript frameworks like Ember.js, Sencha Touch and AngularJS. Nowadays, I'm focused on Angular and related technologies. 46

BEHIND THE CODE MAGAZINE

Which latest feature of Angular is the best because of developer experience? I think animations in Angular is a cool feature, which can bring a lot of energy to the regular web apps.

What do you do in your free time? I play football few times a week and spend time with my lovely wife and kids.

|

NgPoland 2018


ARTICLE

Providing services in Angular by Tomasz Borowski

About services The service can be a simple class that extracts the part of an application’s logic that should not be handled inside the components. One such example is fetching records from the API or preparing data to be displayed. In Angular we can benefit from the Dependency Injection mechanism, which can provide our components with a single instance (singleton) of the service with all of its dependencies automatically resolved. But before we can use our Angular service, we have to provide it somewhere in the application. Here, Angular gives us several choices; the way we choose will determine how and where our service will be available.

Injectable decorator One of the new features added to Angular 6 is an ability to provide a service with @Injectable decorator. We can pass the metadata with the providedIn property set to ‘root’ in order to provide a service in the root injector which makes the service available throughout the application. Additionally, this approach can benefit from treeshaking which happens while building the application, where unused services can be excluded from the final code.

service availability when provided in the root injector NgPoland 2018

| BEHIND THE CODE MAGAZINE

47


ARTICLE Tomasz Borowski

Module providers In order to provide an Angular service, we can also use the providers property in the @NgModule decorator metadata. Service availability will be determined by the way this NgModule is used within the application. If the module is eagerly-loaded into the application (for instance in the AppModule), then its service is provided in the root injector and is available throughout the application. If the module is lazy-loaded (mounted in a certain route by loadChildren property), then its service will be provided in the dedicated module’s child injector. Hence, such a service will be available only for the members rendered within that module. If the module is imported to the eagerly-loaded and lazy-loaded modules (for instance, in some shared module), then its service is provided as separate instances in the related root or child injectors.

service availability when provided in the lazy-loaded module

service availability when provided in the shared module imported in the lazy-loaded and eagerly-loaded modules

48

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


ARTICLE Tomasz Borowski

Component providers Since each component instance has its own injector, we can also provide a service in the providers property of the @Component decorator metadata. Then each instance of that particular component has its own instance of the service and shares it with its subtree of components (descendants).

service availability when provided in the parent component of the eagerlyloaded module

Provided‌ nowhere But before providing a service in the Angular app, we should ask ourselves if we really need to. When we are not injecting any dependencies in such a service and we don’t have to have a single instance of that service, it’s worth considering having it as a simple class which we can just import as and when required. This approach is much easier in use and in testing.

About the author Tomasz Borowski is a Senior Front-End Developer at JCommerce and Trainer at Angular in Space workshops. With 10 years of programming experience, he is currently implementing complex business applications in the Angular framework.

NgPoland 2018

|

BEHIND THE CODE MAGAZINE

49


INTERVIEW Michael Hladky Trainer / Consultant

while(curios) { isLearningPossible = true; } by Michael Hladky

Michael is a developer, trainer and consultant with the focus on Angular and is located in Vienna, Austria. He gives workshops on Angular, RxJs. He is a Google Developer Expert and founder of the Angular-Austria association and Angular-Vienna meetup. Why do you love programming? Michael_Hladky

Being creative without the need of physical things like pen and paper

What do you think about getting involved with the community?

What made you start programming?

I consider community and OOS as the foundation for building software

Curiosity

Which latest feature of Angular is the best because of developer experience?

What do you do in your free time?

Angular CLI add and update commands

Dancing or just hanging out with people I like

50

|

BEHIND THE CODE MAGAZINE

NgPoland 2018



ARTICLE

Meet Scalac A software consulting company that specializes in system development based on Functional Programming languages. Our frontend specialists work with the newest technologies. Developers at Scalac are motivated to learn and grow so working here means working with the Best hAkkers. As we cherish delivering value to the client, we put a lot of effort into our frontend & data engineering teams to create awesome product’s experience & intelligence. We develop great projects for various types of customers. We believe that truly great products happen when employer and employee go hand in hand.

52

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


ARTICLE Scaniac

We work remotely and do our best to fulfill your needs as much as possible, be flexible and provide ideal working conditions. Scalac is also a proud organizer of the Scala Wave Conference.

NgPoland 2018

| BEHIND THE CODE MAGAZINE

53


INTERVIEW Dhananjay Kumar Developer Evangelist/ Organizer ng-India

this.you = Universe.subscribe(attitude => {this.yourattitude = attitude.positivity}); by Dhananjay Kumar

Can you introduce yourself? Like who are you and what do you do? My name is Dhananjay Kumar. I work as Developer Evangelist for Infragisitics. I am a Microsoft MVP since 2010. I organize ngIndia.

Why do you love programming?

debug_mode

It makes me feel that I am solving problems which impact lives.

Did you start your career as a developer? What made you start programming? Yes I started my career as a developer. I did my graduation in Computer Science and Engineering and after that getting a job as developer was obvious progression.

54

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


INTERVIEW

Which latest feature of Angular is the best because of developer experience? I almost love everything in Angular. While solving problem whatever Angular feature helps me I ďŹ nd that best. But to answer your question, I ďŹ nd data bindings , component communications , Change Detentions, Reactive Forms etc very powerful to solve real problems.

What do you do in your free time?

Dhananjay Kumar

What do you think about getting involved with the community? I have been involved with community since 2008. I was just college pass out and started participating in community. Being part of communities helped me getting better jobs, recognition, and exposures. whatever we give to community , it always returns us back. You learn, you teach, you inspire , you get inspired in the community. Everyone should participate in communities.

I love to read and write poetry. I am a poet too.

NgPoland 2018

| BEHIND THE CODE MAGAZINE

55


INTERVIEW Max Koretskyi Developer Advocate at ag-Grid and AngularInDepth

People live like as if they will never die, and die as if they had never lived. by Max Koretskyi

Can you introduce yourself? Like who are you and what do you do? I read sources and teach people fundamentals, write articles and speak at conferences.

Why do you love programming? opportunity for innnovation maxim_koretskyi

Did you start your career as a developer? What made you start programming? I started my career as business consultant, I had to automate a few things and found that I liked programming

What do you think about getting involved with the community? That's a great way to help others and yourself

What do you do in your free time? Sports

56

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


ARTICLE The di erence between NgDoCheck and AsyncPipe in OnPush components by Max Koretskyi (Angular In Depth)

In this article I’m going to show you how to manually work with change detection. These techniques give you a finer control over the comparisons performed automatically by Angular for input bindings and async values checks. Once we have this knowledge, I’ll share with you my thoughts on the performance impact of these solutions.

This article comes as a response to this tweet by Shai. He asks whether it makes sense to use NgDoCheck lifecycle hook to manually compare values instead of using the recommend approach with the async pipe. That’s a very good question that requires a lot of understanding of how things work under the hood: change detection, pipes and lifecycle hooks.

Let’s get started!

NgPoland 2018

|

BEHIND THE CODE MAGAZINE

57


ARTICLE Max Koretskyi

OnPush components In Angular, we have a very common optimization technique that requires adding the ChangeDetectionStrategy.OnPush to a component’s decorator. Suppose we have a simple hierarchy of two components like this:

@Component({ selector: 'a-comp', template: ` <span>I am A component</span> <b-comp></b-comp> ` }) export class AComponent {} @Component({ selector: 'b-comp', template: `<span>I am B component</span>` }) export class BComponent {} With this setup, Angular runs change detection always for both A and B components every single time. If we now add the OnPush strategy for the B component:

@Component({ selector: 'b-comp', template: `<span>I am B component</span>`, changeDetection: ChangeDetectionStrategy.OnPush }) export class BComponent {} Angular will run change detection for the B component only if its input bindings have changed. Since at this point it doesn’t have any bindings, the component will ever only be checked once during the bootstrap.

Triggering change detection manually Is there a way to force change detection on the component B? Yes, we can inject changeDetectorRef and use its method markForCheck to indicate for Angular that this component needs to be checked.

58

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


ARTICLE Max Koretskyi

And since the NgDoCheck hook will still be triggered for B component, that’s where we should call the method: @Component({ selector: 'b-comp', template: `<span>I am B component</span>`, changeDetection: ChangeDetectionStrategy.OnPush }) export class BComponent { constructor(private cd: ChangeDetectorRef) {} ngDoCheck() { this.cd.markForCheck(); } }

Now, the component B will always be checked when Angular checks the parent A component. Let’s now see where we can use it.

Input bindings I told you that Angular only runs change detection for OnPush components when bindings change. So let’s see the example with input bindings. Suppose we have an object that is passed down from the parent component through the inputs:

@Component({ selector: 'b-comp', template: ` <span>I am B component</span> <span>User name: {{user.name}}</span> `, changeDetection: ChangeDetectionStrategy.OnPush }) export class BComponent { @Input() user; }

NgPoland 2018

|

BEHIND THE CODE MAGAZINE

59


ARTICLE Max Koretskyi

In the parent component A we define the object and also implement the changeName method that updates the name of the object when a button is clicked:

@Component({ selector: 'a-comp', template: ` <span>I am A component</span> <button (click)="changeName()">Trigger change detection</button> <b-comp [user]="user"></b-comp> ` }) export class AComponent { user = {name: 'A'}; changeName() { this.user.name = 'B'; } }

If you now run this example, after the first change detection you’re going to see the user’s name printed: User name: A But when we click on the button and change the name in the callback: changeName() { this.user.name = 'B'; }

The name is not updated on the screen. And we know why, that’s because Angular performs shallow comparison for the input parameters and the reference to the user object hasn’t changed. So how can we fix this?

60

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


ARTICLE Max Koretskyi

Well, we can manually check the name and trigger change detection when we detect the difference: @Component({ selector: 'b-comp', template: ` <span>I am B component</span> <span>User name: {{user.name}}</span> `, changeDetection: ChangeDetectionStrategy.OnPush }) export class BComponent { @Input() user; previousName = ''; constructor(private cd: ChangeDetectorRef) {} ngDoCheck() { if (this.previousName !== this.user.name) { this.previousName = this.user.name; this.cd.markForCheck(); } }

If you now run this code, you’re going to see the name updated on the screen.

Asynchronous updates Now, let’s make our example a bit more complex. We’re going to introduce an RxJs based service that emits updates asynchronously. This is similar to what you have in NgRx based architectures.

NgPoland 2018

|

BEHIND THE CODE MAGAZINE

61


ARTICLE

Max Koretskyi

I’m going to use a BehaviorSubject as a source of values because I need to start the stream with an initial value: @Component({ selector: 'a-comp', template: ` <span>I am A component</span> <button (click)="changeName()">Trigger change detection</button> <b-comp [user]="user"></b-comp> ` }) export class AComponent { stream = new BehaviorSubject({name: 'A'}); user = this.stream.asObservable(); changeName() { this.stream.next({name: 'B'}); } }

So we receive this stream of user objects in the child component. We need to subscribe to the stream and check if the values are updated. And the common approach to doing that is to use Async pipe.

Async pipe So here’s the implementation of the child B component: @Component({ selector: 'b-comp', template: ` <span>I am B component</span> <span>User name: {{(user | async).name}}</span> `, changeDetection: ChangeDetectionStrategy.OnPush }) export class BComponent { @Input() user; } But is there another way that doesn't use the pipe? 62

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


ARTICLE Max Koretskyi

Manual check and change detection Yes, we can check the value manually and trigger change detection if needed. Just as with the examples in the beginning, we can use NgDoCheck lifecycle hook for that. Ideally, though, we would want to move our comparison and update logic from NgDoCheck and put it into the subscription callback, because that’s when the new value will be available:

export class BComponent { @Input('user') user$; user = {name: null}; constructor(private cd: ChangeDetectorRef) {} ngOnInit() { this.user$.subscribe((user) => { if (this.user.name !== user.name) { this.cd.markForCheck(); this.user = user; } }) } } What’s interesting is that it’s exactly what the Async pipe is doing under the hood

So which solution is faster? So now that we know how we can use manual change detection instead of the async pipe, let’s answer the question we started with. Who’s faster? Well, it depends on how you compare them, but with everything else being equal, manual approach is going to be faster. I don’t think though that the difference will be tangible. Here are just a few examples why manual approach can be faster. In terms of memory you don’t need to create an instance of a Pipe class. In terms of compilation time the compiler doesn’t have to spend time parsing pipe specific syntax and generating pipe specific output.

NgPoland 2018

|

BEHIND THE CODE MAGAZINE

63


ARTICLE

Max Koretskyi

In terms of runtime, you save yourself a couple of function calls for each change detection run on the component with async pipe. Here’s for example the code for the updateRenderer function generated for the code with pipe:

function (_ck, _v) { var _co = _v.component; var currVal_0 = jit_unwrapValue_7(_v, 3, 0, asyncpipe.transform(_co.user)).name; _ck(_v, 3, 0, currVal_0); } As you can see, the code for the async pipe calls the transform method on the pipe instance to get the new value. The pipe is going to return the latest value it received from the subscription. Compare it to the plain code generated for the manual approach:

function(_ck,_v) { var _co = _v.component; var currVal_0 = _co.user.name; _ck(_v,3,0,currVal_0); } These are the functions executed by Angular when checking B component.

A few more interesting things Unlike input bindings that perform shallow comparison, the async pipe implementation doesn’t perform comparison at all (kudos to Olena Horal for noticing that). It treats every new emission as an update even if it matches the previously emitted value. Here’s the implementation of the parent component A that emits the same object. Despite this fact, Angular still runs change detection for the component B:

export class AComponent { o = {name: 'A'}; user = new BehaviorSubject(this.o); changeName() { this.user.next(this.o); } }

64

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


ARTICLE Max Koretskyi

It means that the component with the async pipe will be marked for check every time a new value is emitted. And Angular will check the component next time it runs change detection even if the value hasn’t changed. Where is this relevant? Well, in our case we’re only interested in the property name from the user object because we use it in the template. We don’t really care about the whole object and the fact that the reference to the object may change. If the name is the same we don’t need to re-render the component. But you can’t avoid that with the async pipe. NgDoCheck is not without the problems on its own :) As the hook is only triggered if the parent component is checked, it won’t be triggered if one of its parent components uses OnPush strategy and is not checked during change detection. So you can’t rely on it to trigger change detection when you receive a new value through a service. In this case, the solution I showed with putting markForCheck in the subscription callback is the way to go.

Conclusion Basically, manual comparison gives you more control over the check. You can define when the component needs to be checked. And this is the same as with many other tools — manual control gives you more flexibility, but you have to know what you’re doing. And to acquire this knowledge, I encourage you to invest time and effort in learning and reading sources. If you’re concerned with how often NgDoCheck lifecycle hook is called or that it’s going to be called more often than the pipe’s transform — don’t. First, I showed the solution above where you don’t use the hook in the manual approach with asynchronous stream. Second, the hook will only be called when the parent component is checked. If the parent component is not checked, the hook is not called. And with regards to the pipe, because of the shallow check and changing references in the stream, you’re going to have the same number of calls or even more with the transform method of the pipe.

Want to learn more about change detection in Angular? Visit Angular In Depth Blog and read other articles. Start with "These 5 articles will make you an Angular Change Detection expert". This series is a must-read if you want to have a solid grasp of the change detection mechanism in Angular. Each article builds upon the information explained in the preceding one and goes from high-level overview down to implementation details with references to the sources.

NgPoland 2018

|

BEHIND THE CODE MAGAZINE

65


INTERVIEW Juan Herrera Google Developer Expert in Angular

life.events.pipe(filter(e => e.positive)).subscribe(console.live) by Juan Herrera

Can you introduce yourself? Like who are you and what do you do? I am the first Google Developer Expert in Angular of Colombia. I am also the Head of Frontend Development at Yuxi Global where I provide consultancy in Angular to different companies. Organizer of Angular Medellin and NgColombia (The first Angular Conference in Latin America). I love creating social web apps. In my spare time I enjoy dancing and singing jdjuan

Did you start your career as a developer? What made you start programming? When I was 14 I met a hacker who decided to teach me how to code. We wrote some C++ programs with Turbo C. It felt very cool. Later on, my brother taught me how to use GameMaker to create videogames by dragging blocks. I created several games. Finally, I enrolled in University where I got my Software Engineer degree.

66

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


INTERVIEW

Juan Herrera

Why do you love programming? Because it is the best mean to change the world. A few billion lines of code have shaped the way we live today, I'd like to write the next billion lines and make sure the world of tomorrow is even better. What do you think about getting involved with the community? It is the only way to do software right. Software has never been about individuals, but communities. Every line of code you write should be clear enough for the next developer. Every product you create should add value to the person using it. At the end, it is always about people, and how we impact them positively

What do you think, which latest feature of Angular is the best because of developer experience? I believe the main headache of Angular developers is migrating over the next major version. When the Angular CLI brough the ng update command, they deďŹ nitely improved the Developer Experience.

NgPoland 2018

|

What do you do in your free time? I like to dance, play guitar, sing, listen to audio books, watch Netix, and play FPS games

BEHIND THE CODE MAGAZINE

67


INTERVIEW MikeHartington Developer Advocate

Can you introduce yourself? Like who are you and what do you do? I'm Mike, a dev advocate for Ionic Framework. I spend my time helping people be success when building apps, working on the framework itself, and building furniture in my free time.

mhartington Why do you love programming? Problem solving and making something out of nothing. It's very satisfying to need to make something, and work through all the problems that come along during the process.

Did you start your career as a developer? What made you start programming? No, I started off as a designing but had a lot of experience in Flash Animation and ActionScript. I started programming out of necessity, as the job I had at the time needed me to make an App.

68

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


INTERVIEW

Mike Hartington

me.tenacity.value > me.talent.value; by Mike Hartington

What do you think about getting involved with the community? The community is almost an essential part of any developers life it feels like. So being involved with the greater developer community feels like it's almost required by everyone.

What do you think, which latest feature/features of Angular is/are the best because of developer experience? The CLI for sure is one of the best features, and the build features that have been built around it.

What do you do in your free time? Build furniture, make music, garden, and relax as much as possible

NgPoland 2018

| BEHIND THE CODE MAGAZINE

69


ARTICLE

Ionic Release: v4 Beta 15 by Mike Hartington (Ionic blog)

Hey there, friends! We’re back at it again with a new beta release of Ionic 4, Beta 15. is release includes several new changes that we thought would be great to talk about, so let’s jump right into it!

CSS Variables Stability CSS Variables are at the core of design in Ionic 4. We can think of them as the standardized “public API” that developers use to customize Ionic’s components. With this in mind, we’re happy to share that we’ve stabilized the CSS Variable API across the Framework. Now that that’s finished, we will be working on improving our documentation to include more information on how Ionic components can be customized. We recently added a new theming section in the docs to give folks a primer on CSS variables as well as a new blog post (expect that soon)

70

BEHIND THE CODE MAGAZINE | NgPoland 2018


ARTICLE Mike Hartington

Material Design Refresh

Material Design is a visual design guide that outlines the standards that apps should follow. Every now and then the guide updates the standards to improve the user experience. In this release, we have begun upgrading our Material Design components to better adhere to the latest guidelines.

The design changes we are implementing are not drastic, but they provide a nativelike experience when they match the specification. This way, your users will always feel at home on whatever platform Ionic is running. While this release does not include a refresh for every Ionic component, we’re working hard to update the rest for future releases.

Rethinking Tabs One of the most valuable and complex components in Ionic’s toolkit is Tabs. Tabs started off as a simple component that would create a tabbed interface to allow users to switch between different views in a way that was consistent with native UX paradigms. Over time, we started hearing people ask for more features to be added: “Can we have one tab button that is just a button?” “Can I customize how the tab buttons are displayed?” “Can I use a custom icon in the tab?” Traditionally, these features, and many others, were difficult to accomplish because Tabs was doing a lot of magic behind the scenes to generate the Tab bar and buttons. With this in mind, we thought it was time for a refresh to offer as much flexibility as possible within Tabs. In order to do this, we had to change how Tabs were written in an app. Prior to Beta 15, Tabs would look like this:

NgPoland 2018

|

BEHIND THE CODE MAGAZINE

71


ARTICLE Mike Hartington

Screenshot Testing Tool Building and maintaining a large UI library used by many developers isn’t an easy task, and even the simplest change can have drastic effects. Recently, our core team started to use a new tool that we built ourselves (we call it Screenshot) to help solve this problem, and to have the confidence in any and all CSS and JS changes. With the introduction of Stencil using Puppeteer, we were able to build out a robust system specifically for team development.

Here’s how it works. On every pull request (PR), a bot is able to automatically take screenshots of each of our end-to-end tests and compare it to the master version. Before merging any PR, our team is asked to approve or deny the changes, so we’re always confident that our thousands of scenarios are passing. The Screenshot homepage always shows the latest master tests, and each PR provides links to specific commit comparisons.

To the Next Beta (or RC?)…. and Beyond! As we’ve progressed through each beta, we’ve gotten a clearer idea of where we want the framework to be by final. I’m happy to say that we’re super close to that, and you can expect it to be just around the corner. Happy hacking, y’all!

72

BEHIND THE CODE MAGAZINE

|

NgPoland 2018



ARTICLE

NestJS - Introduction by Kamil Myśliwiec

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript (preserves compatibility with pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming). Under the hood, Nest makes use of Express, but also provides compatibility with a wide range of other libraries (e.g. Fastify). This allows for easy use of the myriad third-party plugins which are available. In this article, you'll learn the core fundamentals of Nest. To get familiar with the essential building-blocks of Nest applications, we'll build a basic CRUD application with features that cover a lot of ground at an introductory level.

Philosophy In recent years, thanks to Node.js, JavaScript has become the “lingua franca” of the web for both front and backend applications. This has given rise to awesome projects like Angular, React and Vue which improve developer productivity and enable the construction of fast, testable, and extensible frontend applications. However, while plenty of superb libraries, helpers, and tools exist for Node (and server-side JavaScript), none of them effectively solve the main problem architecture. Nest provides an out-of-the-box application architecture which allows for effortless creation of highly testable, scalable, loosely coupled, and easily maintainable applications.

74

BEHIND THE CODE MAGAZINE | NgPoland 2018


ARTICLE Kamil Myśliwiec

Language We're in love with TypeScript, but above all - we love Node.js. That's why Nest is compatible with both TypeScript and pure JavaScript. Nest is taking advantage of latest language features, so to use a framework with simple JavaScript we need a Babel compiler. We'll mostly use TypeScript in the examples we provide, but you can always switch the code snippets to vanilla JavaScript syntax.

Prerequisites Please make sure that Node.js(>= 8.9.0) is installed on your operating system.

Setup Setting up a new project is quite simple with the Nest CLI. With npm installed, you can create a new Nest project with the following commands in your OS terminal: npm i -g @nestjs/cli nest new project-name

The project directory will be scaffolded with several core files being located within a src/ directory.

src

app.controller.ts app.modules.ts main.ts

Following the convention, newly created modules should have their dedicated directory.

The entry file of the application. It uses NestFactory to create the Nest application instance. Defines AppModule, the root module of the application.

main.ts app.module.ts app.controller.ts

Basic controller sample with a single route.

NgPoland 2018

|

BEHIND THE CODE MAGAZINE

75


ARTICLE Kamil Myśliwiec

The main.ts includes an async function, which will bootstrap our application:

To create a Nest application instance, we are using the NestFactory. NestFactory is one of the most fundamental classes, it exposes a few static methods that allows creating application instance. The create() method returns an object, which fulfills the INestApplication interface, and provides a set of usable methods which are well described in the next chapters.

Running application Once the installation process is complete, you can run the following command to start the HTTP server: npm run start

This command starts the HTTP server on the port defined inside the src/main.ts file. While the application is running, open your browser and navigate to http://localhost:3000/. You should see the Hello world! message.

Stay in touch Author: Website: Twitter:

Kamil Myśliwiec https://nestjs.com @nestframework

Support us Nest is an MIT-licensed open source project. It can grow thanks to the support by these awesome people. If you'd like to join them, please read more here: https://docs.nestjs.com/support

76

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


INTERVIEW Vitalii Bobrov Senior Software Engineer

if (fadeAway) return burnOut; by Vitalii Bobrov

Can you introduce yourself? Like who are you and what do you do? I'm a JavaScript Engineer with more than ďŹ ve years of professional experience. Also, I'm a co-organizer of Angular Wroclaw meetup. I'm trying to keep up-to-date with the latest Web Platform features and doing great experiments with it. I'm not just a nerd, but tech speaker, ngGirls mentor, and the father of the excellent little girl. bobrov1989 Did you start your career as a developer? What made you start programming?

Even after more than 6 years of doing this, sometimes it still feels like a magic.

Yes, I started as FE and Drupal (PHP).

Which latest feature of Angular is the best because of developer experience? Schematics

Why do you love programming?

What do you do in your free time? Spend time with family

NgPoland 2018

| BEHIND THE CODE MAGAZINE

77


INTERVIEW Wassim Chegham Head of Open Source at SFEIR Can you introduce yourself? Like who are you and what do you do? I'm Wassim, I lead the Open Source ofďŹ ce at SFEIR. I'm the author of a bunch of open source projects such as xlayers.app and ngx.tools. I'm also a GDE and an advocate for the Angular core team, the Google Assistant and the GCP teams at Google. I'm a member of the Node.js Foundation helping out as a mentor. I was also a former member of the Angular Universal core team and I'm currently part of the Angular Console and Compodoc core teams.

manekinekko Why do you love programming?

I've been fascinated by programming and coding since I was little, because to me Programming is kind of an Art. I feel like an artist when I'm solving real world problems with Code. Did you start your career as a developer? What made you start programming? When I was little, I was always looking to understand how things worked, like TV sets, electronic toys, DVRs and computers. That's why I've decided to study STEM and eventually switched to Computer Science. So, when I graduated from Univertsity as an engineer in Computer Science, I did my internship at a consultancy company, then went through many roles: from a junior engineer to a senior developer, then to a tech leader and team leader; and more recently I had a Sr. Developer Advocate (DA) role. Currently, I work fulltime in open source and lead our open source strategy at SFEIR. 78

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


INTERVIEW

Wassim Chegham

Learn. Think. Create. Share. by Wassim Chegham

What do you think about getting involved with the community? At school we are taught how to think, we learnt all the theory and concepts of programming and computer science, but the practice comes from the real life projects. So, as many of us, I learnt a lot from the community when I was student and junior developer; the community taught me how to become a better developer. Now, It's my turn, my passion, to help others, in any manner. I've been doing this for the last 5 years and it feels great! Because I also keep learning from the community, it's not only one way. It's a continuous process of learning and giving back.

What do you think, which latest feature of Angular is the best because of developer experience? My first favorite upcoming feature of Angular is the new build system with Bazel. I'm definitely confident it's gonna change and improve drastically the DX for Angular developers. My second favorite feature is of course the new renderer (or compiler). With IVy Angular will become fully and finally interoperable with any library and framework. That will open so many doors for so many new possibilites. Trust me!

What do you do in your free time? When I'm not coding or merging pull requests, I usually spend some time learning about music composition, especially EDM. I also like drawing, photography and travelling all around the world.

NgPoland 2018

|

BEHIND THE CODE MAGAZINE

79


INTERVIEW Maye Edwin Creating PWAFire.Org For The Web

<code> Life </code> by Maye Edwin

Can you introduce yourself? Like who are you and what do you do? I Am Creating PWAFire.Org For The Web, Speaking On Web Technologies ( Mostly Progressive Web Apps/First Experiences) And Randomly On Developer Community Leadership. Find More About Me With #MeetMaye On Twitter

MayeEdwin1 Did you start your career as a developer? What made you start programming? Yeah. When I went for Bsc. Computer Science Though wanted to be a Quantity Surveyor : )

What do you think about getting involved with the community?

Why do you love programming? ou can create something that can change lives if lots of people and that's just amazing : )

Which latest feature of Angular is the best because of developer experience? Everything About Angular 7

80

BEHIND THE CODE MAGAZINE

I am a product of community. It's amazing when you can share, learn and connect with fellow devs in the community. You become much better when you're part of one, two or more What do you do in your free time? Writing on my Medium publication and Playing FIFA

|

NgPoland 2018


INTERVIEW William Grasel Tech Lead and Software Engineer

life.ďŹ lter(task => task.hasMeaning()).map(t => t.doWithLove()).share().subscribe() by William Grasel

Can you introduce yourself? Like who are you and what do you do? I'm a web developer for 15 years, open source contributor, speaker, community coordinator, teacher, Angular consultant and Google Developer Expert. I'm a fan of technology, games, movies and series. Love bikes, martial arts and meditation. Trying to make the world a little bit better. Why do you love programming? willgmbr

So we can make and create a lot of new things that were impossible before.

Did you start your career as a developer? What made you start programming? Yes, I started as a developer 'cause I was always in love with computer and technology, so I wanted to understand how it works.

Which latest feature of Angular is the best because of developer experience?

It is one of the most important things in the area, because the way technology evolves makes it impossible to go ahead without a strong way of continuous sharing of knowledge.

What do you do in your free time?

Schematics are one of the most revolutionary things recently, and I believe with time it will be copied for everyone, even in other ecosystems out of front end and JavaScript. NgPoland 2018

What do you think about getting involved with the community?

|

I play video games, watch series and movies, and of course study and organize community related things.

BEHIND THE CODE MAGAZINE

81


INTERVIEW Maxim Salnikov PWAdvocate

webmaxru

Maxim Salnikov is Oslo-based Web Full-Stack Engineer, a Google Developer Expert in Web Technologies & IoT, and a Microsoft MVP in Development Technologies. He architects complex web applications since the end of the last century and has extensive experience with all aspects of web platform focusing on the apps managing real-time data from IoT devices and Progressive Web Apps. Maxim is a founder and active contributor to two conferences: Mobile Era and ngVikings Nordics’ main conferences for mobile and Angular developers respectively. Also, he leads Norway’s largest meetups dedicated to web front-end and mobile: Angular Oslo, Mobile Meetup, Oslo PWA. Maxim is passionate about sharing his web platform experience and knowledge with the community. He travels extensively for visiting developers events and speaking/training at conferences and meetups around the world.

82

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


INTERVIEW The best learning is teaching by Maxim Salnikov

Why do you love programming? This is keeping my brain entertained

Did you start your career as a developer? What made you start programming? I loved computers from my early ages, so becoming a developer was very natural move for me

What do you think about getting involved with the community? This is a must have for the web-developers. Technology develops so fast that only the continuous communication with the soulmates will keep you up to date. Plus, IT-people are the awesome folks to chat with!

Which latest feature of Angular is the best because of developer experience? Angular Service Worker - main PWA automation tasks out-of-the-box

What do you do in your free time? I organize and speak at the conferences = I travel and communicate with many awesome people

NgPoland 2018

| BEHIND THE CODE MAGAZINE

83


INTERVIEW Sani Yusuf Founder Haibrid

Only those who see the invincible can achieve the impossible. Impossible is nothing. Can you introduce yourself? Like who are you and what do you do? I am a software engineer currently focusing on Angular and Ionic. I do a lot of Architecture stuff and love writing efďŹ cient code that is re-usable across teams

Why do you love programming? It allows me to take something in my head and make it a reality & then watch people use it to make their lives better.

saniyusuf Did you start your career as a developer? What made you start programming? I started as a developer yes. I was self taught, then I went to university for it.

Which latest feature of Angular is the best because of developer experience? I like Reactive Forms. I really think the best feature. It is well written and well abstracted. I also like the ability to add projects from the CLI

84

BEHIND THE CODE MAGAZINE

What do you think about getting involved with the community? I recommend this move. You will learn way much more if you get into this area. Also you will be way much more employable if you write open source or start attending meetups as your network will grow. What do you do in your free time?

I watch Arsenal play football and watch TV shows.

|

NgPoland 2018


INTERVIEW Dmitriy Shekhovtsov CTO

We gonna make it! by Dmitriy Shekhovtsov

Author of Valor Software, ngx-bootstrap and ngTalks conf, GDE in Angular valorkin Did you start your career as a developer? What made you start programming? I am programming since 6 years old, at that time to play game you had to code it manually

Which latest feature of Angular is the best because of developer experience? Ivy

Why do you love programming? This is kinda magic

What do you do in your free time? Work

NgPoland 2018

| BEHIND THE CODE MAGAZINE

85


INTERVIEW Jorge Cano Full Stack Developer

After more than 10 years working in the tech industry, Jorge is a full stack developer with focus on JavaScript technologies. Today, Jorge is working at Byte Default using Angular / RxJS / Firebase / Nativescript as well as other technologies. He delivered several courses and talks as well as write some tech articles on these subjects. Because of that, he was recognised as a Google Developer Expert in Angular & web technologies and Nativescript Developer Expert by telerik. jorgeucano Why do you love programming? Since I understood the potential of programming, I understood that there are no borders or limits, you will only get to where you want to go ... therefore I set out to do great things (I come pretty well xD) ... but I think that what more I love that we do not need anything more than an idea and desire to make it come true. Did you start your career as a developer? What made you start programming? I always found it appealing to understand how the software worked ... when I finished school, I went to the "Technological University of Argentina" and there was a "software architect" course (based on java) taught by Sun Microsystems ... and there I learned to program on paper, doing desk tests, understanding the difference and the importance of good architecture, among other things ... and those were my first steps in this magnificent world. 86

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


INTERVIEW Jorge Cano

if ( !people.can ) { jorge.helpYou() } by Jorge Cano

What do you think about getting involved with the community? Many years ago, after having several jobs where employees did not share their knowledge, I got a job where I could have my "nerd talks" and talk about the functions we wrote and how we had done to improve the performance and things like that. .. This made me believe that there were people who wanted to share their knowledge, there I met the "Google Developers Group" and I got involved and involved, trying to help, giving talks, making videos and sharing my knowledge ... Since then, about 5 years ago, I dedicated myself every day to help and share my knowledge, it seemed something fantastic, thanks to the community I learned a lot and I was able to help others with what I knew. Today, I wrote a book (about angular), I gave courses in the four most important platforms of Spanish courses, last year I gave 52 lectures, 12 workshops and some trainings ... And this year I continued with this (not with those numbers) but trying to get important themes (for me) such as Angular, RxJS, Bazel, scalable architectures, Angular, NgRX, Firebase, Nativescript among other things What do you think, which latest feature of Angular is the best because of developer experience? I really LOVE the CDK, I think it's one of the most fantastic things that happened to Angular's team, giving us a library so that the performance of our view is incredibly fast and well done is great ... the virtual scroll is something FANTASTIC

What do you do in your free time? If I'm not writing a new post, traveling to a conference, putting together a talk or a workshop ... I like to enjoy a good book (I'm a fan of Tolkien and Patrick Rothfuss) I really like the "Fantastic Literature" ... but I also like to play on my consoles, so I try to mix my free time between the community and reading a good book ...

NgPoland 2018

| BEHIND THE CODE MAGAZINE

87


ARTICLE How `runOutsideAngular` might reduce change detection calls in your app by Krzysztof Grzybek

When working with Angular, I often see people are confused about NgZone and zone.js itself. I think that many developers treat it like black box, because they assume that Angular handles change detection auto-magically and they don’t even have to care about zones. Well, in most cases that’s true, but… In this short post I will show You 3 cases where NgZone.runOutsideAngular might reduce significantly amount of change detection calls in Your app (which might improve overall performance). I won’t explain details about NgZone and zone.js in this post, because there a lot of resources about that, but I hope You will be inspired to learn more about this topic.

Frequent timers Ok, let’s take a look at first case. It might occurs in every place where You fire timers frequently, like setInterval, setTimeout or requestAnimationFrame. Let’s say we have to do some canvas animation inside our angular app. Our animation loop is simple setInterval. this.interval = window.setInterval(() => { this.setNextColor() this.paint(); }, 10); Every 10ms our canvas is updated with new color. Looks fine, right? Now open console in devTools. Each time change detection is triggered, You will see log ‘Change detection triggered’.

88

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


ARTICLE Krzysztof Grzybek

Oh my, looks like something went wrong! How did it happened? By default, change detection is triggered every time when last function in call stack is executed — if it’s in the NgZone. (it’s actually very simplified, but basically that’s how it works). So every 10ms we put callback from setInterval on the call stack, and after execution of this function, change detection is triggered on the root component. Angular doesn’t care that we don’t need it at all! But, as You probably assume, there’s a simple way to fix it. You can just wrap it with NgZone.runOutsideAngular like this:

this.ngZone.runOutsideAngular(() => { this.interval = window.setInterval(() => { this.setNextColor() this.paint(); }, 10) }); And just enjoy clear console. Why is that? Because now we run timers outside NgZone and angular isn’t even “aware” that we fire these timers.

Outside clicks Second case: You want to react on click outside Your component. Typical situation for stuff like dropdown, select input or popup. So what You probably would do is to bind @HostListener to document and check if component host contains event target. @HostListener('document:click', ['$event']) onDocumentClick(e: MouseEvent) { if (!this.elRef.nativeElement.contains(e.target)) { this.dropdownOpened = false; } } This cause additional change detection on each document click. If we have 10 dropdowns on page, it would make additional 10 change detection calls on each click! Let’s use our tools to improve that. Because event listener was bound in NgZone, after each callback, views has to be checked for changes, so we want to bind listener outside NgZone. We want to be aware of state changes when click triggers dropdown close, so we have to get back to the Zone when needed.

NgPoland 2018

|

BEHIND THE CODE MAGAZINE

89


ARTICLE Krzysztof Grzybek

ngOnInit() { this.ngZone.runOutsideAngular(() => { this.document.addEventListener( 'click', this.onDocumentClick.bind(this) ); }); } onDocumentClick(e: MouseEvent) { if ( !this.elRef.nativeElement.contains(e.target) && this.dropdownOpened ){ this.ngZone.run(() => { this.dropdownOpened = false; }); } }

Ok, now it works better:

Non-angular components integration Let’s move to third case, the last one I’m gonna show you. It’s about creating angular components based on vanilla js or jquery plugins packages. Let’s say we need color picker component. We can write it from scratch, but why reinvent the wheel if there are non angular, stable solutions? We can just wrap it in angular component and we’re ready to go. So we may do something like this:

ngOnInit() { $(this.colorPickerEl.nativeElement).spectrum({ change: (c) => { this.change.emit(c.toHexString()); } }); } 90

BEHIND THE CODE MAGAZINE

|

NgPoland 2018


ARTICLE Krzysztof Grzybek

Change detection is fired after every time mousemove callback is finished. It’s because event listener was added in NgZone. To fix it, let’s just initialize plugin outside NgZone, and get back only if there’s a need to do it (e.g. we update angular component property value) ngOnInit() { this.ngZone.runOutsideAngular(() => { $(this.colorPickerEl.nativeElement).spectrum({ change: (c) => { this.ngZone.run(() => { this.change.emit(c.toHexString()); }); } }); }); }

Let’s see how it behaves after this change: Decent!

Summary We examined 3 cases where runOutsideAngular can reduce significantly amount of changeDetection calls. In simple apps, You probably won’t spot the performance improvements, but in robust apps, or some specific cases it might be a nice boost. Notice that it required from us just a little tweak in our code and understating of zones. I hope that this will inspire You to increase your knowledge about zone.js and NgZone. All examples from this post are available on Github here: https://github.com/krzysztof-grzybek/Run-outside-angular-examples

NgPoland 2018

|

BEHIND THE CODE MAGAZINE

91



Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.