10 answers from our deep dive into Angular with Ken Rimple - Technical.ly Philly

Dev

Aug. 16, 2017 10:15 am

10 answers from our deep dive into Angular with Ken Rimple

Suggestions for Angular beginners, a detailed look at the differences between the new and old versions of Angular and more. Much more.

Ken Rimple.

(Photo courtesy of Emily Melendez)

We at Technical.ly don’t often get into the nitty gritty of technical topics because we’re journalists first, not developers. But that doesn’t mean we don’t want those kinds of stories on our site.

In our latest experiment to produce more detail-oriented dev content and to try a new editorial feature for our Technical.ly Talent recruiting product, we ran an office hours session on Angular with Ken Rimple of Chariot Solutions on our public Slack (here’s where to snag an invite).

Check out a lightly edited transcript of the conversation below. (Some of the questions were submitted beforehand by people who didn’t attend the office hours session.)

###

While we’re getting started, I wanted to send out a few suggestions for beginners…

1) Angular is the “new” name of “Angular 2”. They decided to rename the “2” and higher versions plain old “Angular” recently (six months or so ago) since the version number will change major versions for each breaking framework change. We’re already on Angular 4.3.1 (or maybe .2) at this point, and by the end of the summer they will go to 5. My amps go to 11.

2) AngularJS is what they call the 1.x branch.

3) Googling is now super difficult, because “back in the day” people called AngularJS “Angular”, and all of the blogs that were reasoning about Angular called it “Angular2”, “Angular” etc… So check the date of the blog post when you find a solution, and read carefully. You might be reading something outdated, or something about AngularJS by accident.

4) A GREAT place to learn about the happenings and ask questions that are deeper in tech focus is Gitter. The URL gitter.im/angular/angular (it kind of follows the GitHub URL) is a live chat stream with lots of committers on it. I wouldn’t ask “how do I get Angular to work” questions there, but if you’re stumped with a feature and there is no good documentation on it, sometimes someone there can be a godsend.

It’s more for specific code problems and such than strategems.

Advertisement

5) I have written a lot of blog articles in the past on http://chariotsolutions.com/blog about AngularJS, Angular etc… Look for the newer ones on specific topics. It was mostly out of my concern to learn about how this stuff works while I was developing my training courseware and teaching others that caused me to blog. I’ll post a few of these and my favorite other external resources as we go along.

To try out Angular in a non-threatening environment (i.e your browser)

Use Plunker.

Click “Launch the Editor” and when in there, click the arrow on the green “New” button at the top.

Pull down to Angular and click it

Viola! A TypeScript Angular app to play with.

You can even download it as a zipfile to play with later.

If you want to play with it later, do this

# unzip your zipfile here
npm install -g live-server
live-server .

Mike Trischetta asks: I’m a full-stack dev with a front-end focus, and only limited exposure to Angular 4. I have a question about modular CSS in Angular 4 models. While I think this is a brilliant feature, I don’t like how it uses vanilla CSS. I love using SCSS and would probably never give it up. Is there any way to marry the two?

Ken Rimple: Oh, yes, you can. If you’ve installed node-sass you can use scss files instead…  Just make sure node-sass is installed, and use away.

Let me see if there is anything you have to set – I know I got it working right off but it may just be that dependency.

Mike Trischetta: oh thank god. haha. And you can include global variables/mixins/functions and use them in any module? That’s the big selling point for me

Ken Rimple: yes

I know I’ve done it.

And anything truly global can go in a css / scss file included with import

so it’s not compartmentalized.

I use it in https://github.com/krimple/drumlegend

Mike Trischetta: did you use the scss in a model? I see the global one so far

Ken Rimple: look in src/app/drum-legend

drum-legend-component.scss

I’m testing it now in an empty app, it’s using scss compilation as long as you use StyleUrls: [‘myfile.scss’]

I’ve already gotten a bonus syntax error in my sample :slightly_smiling_face:

from scss

put your globals in app.scss

sorry styles.scss

checking on how it’s loaded instead of styles.css… hold on

look at .angular-cli.json

the apps[0].styles array

and also you can set a default extension at the defaults area for creating new ones

Also for those of you who are experimenting with creating a new app, there are a bunch of options on the `ng` command that let you do things like make the styles or templates inline by default, etc…

(that’s in the angular-cli)

Jag Talon asks: What’s the difference between the old Angular and the new Angular?

Ken Rimple: ha haaaa! GOOD ONE.

Angular 1.x – written back in 2008, updated since then with major feature changes and additions. Assumes you run browsers on JavaScript 1.5 and higher. It uses symbol-based dependency injection to find object (a.k.a. by their parameter name) and has hacks for passing in strings in case you minimize your code. The hallmark of 1.x, AngularJS as we’d call it, is two-way data binding. You bind a field to a variable. The variable changes, the field does too, and vice versa. Demos really, reallly well and prototypes well.

So, AngularJS (Angular 1.x) has some issues…

performance is the #1 issue

Imagine creating a “spreadsheet” of editable fields. Business people want this kind of thing. If you use two-way binding to bind up all of the fields from, let’s say, an array of objects, and you want it to quickly update _some_ of those objects via a data feed, AngularJS (1.x) can start to slow down appreciably as you get more and more bound objects. There are things you can do to help yourself, but in the end, you’re hacking with AngularJS’s _digest cycle_, which gets triggered every time you make a change.

There are things you can do to help yourself – only two-way bind some fields (those you edit). Only one-way bind (live binding) some fields, and use one-time (on the way up) binding of others.

You can set up something called Track By on your repeated fields, and that can help.

But in the end, when you get north of, say a few thousand things being watched, AngularJs starts to crawl.

So it was architected in 2009, and was very successful, and if you use it right, you really get a lot out of it. We have customers still on 1.x for the practical reasons that it’s too expensive to re-write an entire app.

And it works, so, so what!

Anyway, the status of 1.x – it’s on version 1.6.x right now, and they’re committed to supporting it for the foreseeable future. They will eventually retire it, but keep in mind, Google (who sponsors the team including creator Misko Hevery) still has a lot of apps written in 1.x.

So that’x Angular 1 (ahem, AngularJS)

Angular > 1 (nee Angular 2, nee Angular 4)

Call the new framework Angular

Misko himself stated it was time to rebuild the AngularJS API from the ground up back in 2014.

Reason? It’s got lots of patches to the original.

It’s not built for modern browsers.

It’s not built for things like JS module systems, reactive app development. Sure, you could get things like that going in AngularJS, but it’s not built for it. It basically is a powerful single-page app platform that uses promises to resolve async work (they have a service called $q that creates promises).

So, enter Angular. The design goals:

– make it small
– make it fast
– make it fast
– make it fast
– make it in a language that is easier to find bugs in. Enter TypeScript, the type-based language that looks quite like modern JavaScript but adds datatypes.
– make it reactive – i.e. allow streams of events that can be handled in near real time efficiently
– make it truly modular – use any of the modern module loading systems, specifically SystemJS, or WebPack, to build from a series of node modules for your source code.
– make it testable as like AngularJS
– make it fast

(ba bump bump)

Examples of the major changes from AngularJS to Angular

1) No more pure controllers and views. We now have true _components_

example:

typescript @Component({ template: ` <p>Hello from {{ whom }}</p> ` }) export class HelloComponent implements OnInit { ngOnInit() { this.whom = 'Me!'; } }

A component has a template, controls a view that runs within it, and has code in its class

before it’d be:
JavaScript file:

javascript angular.module('myModule') .controller('HelloController', function($scope) { $scope.whom = 'Me!'; });

HTML template:

html <p ng-controller="HelloController">Hello from {{ whom }}</p>

that’s a major innovation. You can even embed CSS styles within your component as a property in that `@Component` section, and it namespaces them so they don’t collide with other components. And on, and on.

Also, you have types!

typescript const MAX_TRIES: number = 234;

and classes

typescript class Foo { let bar; constructor(bar) { this.bar = bar; } aCoderWalksIntoA() { this.bar = "bar!" } }

Arrow functions – anonymous functions that grab the outside scope

typescript getData() { http.get('/foo/bar') .toPromise() .then( (result) => { this.result = result } ... }

Another thing the Angular team did was that they brought in a framework called RxJS (Reactive JavaScript). It was originally sponsored by Microsoft (btw Microsoft currently sponsors TypeScript)

Super powerful, and it’s a replacement of Promises for anything stream-based.

Everybody who is interested in Angular (the new one) should read this:

http://slides.com/robwormald/everything-is-a-stream

Rob Wormald is a huge committer in the Angular and RxJS world. He’s brilliant, and this is a brilliant talk.

RxJS comes as the internal piping in Angular

It lets you subscribe to a stream of events from a thing called an _observable_

The old observer pattern, functionally.

RxJS has rich features for reasoning about streams

aggregate data, map it, transform it, debounce it, you name it.

And that comes along with Angular.

Angular uses it for things like the route instructions (watch changes in the component as it gets new values), input fields (a valueChanges property that you can subscribe to to watch input change), HTTP API fetches, etc.

So the two biggest things are RxJS and TypeScript IMO

The APIs are rewritten from scratch. Which can pose a problem when you’re trying to learn it and you have an AngularJS background.

It. is. different.

So, you have to deal with it like a whole new framework inspired by the old one.

Rich Freedman asks: Please show us the http example with Observables instead of Promises….

Ken Rimple: NO! :slightly_smiling_face: yes.

give me a moment, I’m going to steal one from one of my projects instead

typescript getTimecards(): Observable<Timecard[]> { return this.http.get('http://localhost:3000/timecards') .map((response: Response) => { return response.json(); }); }

so, you can return an observable stream from a method.

the `this.http.get` returns an Observable.

how did I get http into this?

constructor(private http: Http) { }

In the class I can inject it from a constructor

I can tell it to map the response into something else when it fetches

(hence the .map above)

.map takes the input data, and transforms it something else. Http returns a Response object, with a method called `.json()` which parses Json into an object.

Some of this has changed in 4.3.1, the recent release, because they dropped a new package on us, `@angular/common/httpClient`

which simplifies some of this code even further and gives us a good testing framework for http.

So…

calling that `getTimecards()` method

typescript loadTimeCards() { this.timecardService.getTimecards() .subscribe( (timecards: Timecard[]) => { this.timecards = timecards; }, (error) => { console.log('bad things...', error); }, () => { console.log('http get finished'); }); }

(context note – I put that method in a _service_, which officially is called a Provider in Angular now, but we call them services anyway) –

Subscribe subscribes to an observable. That makes it “hot” – executes the code that is attached to it, if nothing else is.

the first callback in subscribe gets a message delivered to the subscriber (i.e. our payload)

the second callback is for handling errors

the third lets us know the subscription closes

Now, here’s where Angular is a bit odd. They let HTTP APIs like GET, PUT, POST, DELETE, work with Observables. But they’re mostly one-shot beasts.

It was one of the earliest APIs they wired up.

The benefit of doing them like this is the ability to use the RxJS operators on them.

The downside is it’s a tad more complex. But not really, if you consider an Observable like a Promise with zero or more answers.

It’s better to look at things that have a long life with Observables

like this:

private subscribe(device, deviceInfo) { console.log('subscribed!'); const self = this; console.log(`opening connection to ${device.name}`); device.open() .then((subscription) => { subscription.onmidimessage = (data) => { setTimeout(() => { self.dataStream$.next( new MidiMessage(device.name, device.id, device.deviceCategory, data)); }, 0); }; }); }

Let’s chew on this a bit.

in this one, I’m taking a Midi music device, subscribing to it (this is in https://github.com/krimple/drumlegend)

that API is the Chrome MIDI API

it’s promise-driven (the ‘device().open().then thing)

but I have this thing in there

`self.dataStream$`

it’s an observable that _I_ created

So, I subscribe to the MIDI interface’s message stream (which btw is not RxJS, it’s the MIDI API), I

`emit` a message to my own stream

using `.next(message)`

something else picks it up, and does something with it

something like this

typescript messageStream$ .filter((message: MidiMessage) => message.deviceName === 'KMC MultiPad' && message.velocity > 0 && message.messageType === MidiMessageType.VM_KEY_DOWN && (message.noteNumber === 38 || message.noteNumber === 50)) .debounceTime(10) .subscribe((message: MidiMessage) => { if (message.noteNumber === 38) { self.gameHolderService.playLeft(); } if (message.noteNumber === 50) { self.gameHolderService.playRight(); } });

so, just eye this up

we have a messageStream$ thing

it’s a stream of message notes

I’ve made up my own class, MidiMessage

Passing it information from each note sent (a tap on a drum pad or keyboard)

I `filter` it – i.e. only look for a specific device, that the message is a keyboard key down, and it’s in a range)

then I only take them every 10 milliseconds

so that’s what I subscribe to – only messages from a _specific_ device, for a specific type of note playing style, and every so often (in a game, you can tap too quickly by dragging the drumstick on the pad, so I wanted only one note).

RxJS lets you compose streams of data, filter out what you don’t want, and only subscribe to what you want.

In the subscribe there, I say if we hit MIDI note 38, I send the game a message to play a sample of a tom tom

If we hit MIDI note 50, I tell it to play the snare

The fact that I could make streams of data, and reason about them from just about any type of subscriber makes RxJS powerful.

2) Typescript – it’s a tough learning curve at first. You can eventually come to terms with it, and get a lot done. The main thing to remember about TypeScript is that it all ends up transpiled into a soup of JavaScript 1.5 for running in your browser (until we can finally run native ES2015 JavaScript, the modern type)

Don’t assume TypeScript is as good as Java or Scala or C. It’s not. It’s really, really useful at spotting type issues, and at providing you most of the features (if not all) of ES2015 (arrow functions, let/const, etc).

But think of it more as a typed version of ES2015 than C or something that powerful.

3) RxJS is another learning curve, and well worth it _if_ you need that type of flow of data.

But you’ll really want to study how things work. I love the following site:

http://rxmarbles.com/

And again, it’s all embedded in the Angular game.

ok, don’t let me suppress any questions.

In short, try THAT with promises.

So, Angular is much more powerful than AngularJS.

Here are the things to concern yourself with using Angular.

1) documentation, it’s not so great. They have a few people on the team who like to write stories, and so a lot of their documentation is locked up in this “Tour of Heroes” narrative. While it is a great piece of tutorial, it’s not user friendly to developers who want atomic answers to basic questions.

They don’t even have all of their core documentation up to date

So Angular is not nearly as mature documentation-wise as AngularJS, which has been around for almost 10 years, is.

Some of the docs are non-existent, but they are getting better.

It helps you visualize how these observables work.

3) everything moves fast in Angular – the standards are evolving, the API is evolving. It’s not as mature as AngularJS so there are additional pieces added. It’s good to stay informed and consider refactoring slightly. Consider the new HttpClient API. It’s finally got some of the features we have in AngularJS with ngMock and the `$httpBackend`. I wrote a blog article in September on how to test with Angular (2 at the time) http://chariotsolutions.com/blog/post/testing-angular-2-0-x-services-http-jasmine-karma/ – now that’s not needed as much

Jason Cox asks: What are some tricks you use to keep your code DRY (Don’t Repeat Yourself :P) using Angular?

Ken Rimple: Use TypeScript to define classes for your data

Break UIs into components

Use @Input and @Output to send and receive data from your smaller components

Use services for all backend logic

Use CSS within the component itself to avoid the 1,000 line CSS file that makes zero sense to anyone ever

and scss to set up globals for themes etc

Use pipes (the successor to filters) to do formatting instead of complex expressions

Learn RxJS as it can do a lot of what you do in loops etc functionally (edited)

Learn to use arrow functions to make your code a tad more concise. Use const for variables that don’t change. use let instead of var everywhere else – you get local scope in if statements, blocks, etc.

Rich, I saw you typing there… Do you have anything you want to jump on (Rich works at Chariot with me and is on a long-term Angular 4 project)

(not trying to out you for thinking 😉

The nice thing about Angular is, it’s 1000% easier to write re-usable components than the AngularJS directive API was.

So you start thinking in components. React isn’t much different BTW in this regard.

Oh, here’s one.

There are two major forms APIs

directive-based forms, and what they call ReactiveForms. the directive-based forms (with validation baked into directives) is the default.

Rich Freedman: Was just gonna add – make modules out of everything. It helps to enforce good structure, and you can always pull a module out and make it an npm module (if you can figure out how) 🙂

Well, I figured out a “good enough” way for internal use. Won’t work for general release.

There’s lots of discussion with the angular team about having the cli or some other tool make it easy to create npm modules from components, etc., but it’s still just talk.

Basically, if you want to publish components as npm modules internally, and your only consumers will be other angular projects, you can ‘cheat’ and just publish the Typescript source.

Ken Rimple: Now, to riff on what Rich is saying, at ng-conf this spring, which both of us attended, they talked about documenting creating an ng module.

(ng = angular)

i.e. an NPM module that is natively able to be consumed.

I took pages of notes.

I tried.

It kinda works.

But it’s not for the feint-hearted.

So… Long-term, the Angular team will have documentation and probably a mechanism built into the Angular CLI to create a NPM module so you can create projects for your widgets without having to pull them into source yourself.

Other projects do this, look at ng2-material-design for example.

any widget maker project.

it’s just not obvious. I was working on a blog article on it, but figured it would improve. Maybe that’s an August project for me…

Jason Cox asks: Which do you think wins in terms of code reuse out of Angular and React?

Ken Rimple: Hmm. Great question.

Inside baseball here… I am currently wrapping up updates on our React course. We wanted a better lab, and we made a word matching game for it.

So I’m intimately familiar with both Angular 4 and React these days.

Code-reuse-wise… I think Angular has the advantage out of box because of TypeScript and the fact that it is a framework with all of the basic parts you need.

You _can_ get the same productivity out of React

You can install TypeSCript

OR Flow, the Facebook types API

You CAN install RxJS

In fact, Redux is the most popular state management engine for React, and what did some Angular developers do?

They created this AWESOME thing

https://github.com/ngrx/store

It uses RxJS in Angular to hold state.

I’m using it for the Drum Legend game.

So, Angular can do the whole state management game Redux does, and with RxJS so you get that great functional composability too

On the react side, let’s look

React is JUST the component library.

The view as it were

You need to install

a) an Ajax library (axios? Fetch? jQuery? etc)

b) a router (the React Router v4 is the defacto one)

c) some sort of type management so typescript or flow

d) state management would come in with things like Redux

there are various other projects.

All to get what you get out of box in Angular.

Also, you go away from it for six months…

You do npm install – it gets new updated versions of things that all run at different speeds development-wise.

At least Angular 4.3.1 comes with its own Ajax, router, animations API, RxJS support, etc.

Now on the React side, not to be 100% biased, there are lots of starter projects. Including the official one from React, ‘create-react-app’. We use that in our training, and then install the libraries we want (which include currently redux, axios, redux-saga, thunk, and react-router)

it works great, and I can see why you might want to use React in some projects. The core framework is small. So small that it’s really quick to boot up. The tooling is less to get what you want.

But you’d need to be a much more adept NodeJS / JavaScript expert to be good at React IMO.

Enterprise developers can get going with a reasonable learning curve with Angular.

But web developers would mostly prefer React first. Until they peel away the layers of the onion and find empty space and then have to install other stuff for just the basics.

So, just as a shameless plug, we offer training in both React and Angular.

http://chariotsolutions.com/course/angular-workshop-fundamentals-architecture/ for Angular

http://chariotsolutions.com/course/react-friends-introduction-react-redux-react-router-supporting-apis/ for React

and even two classes for AngularJS if you are using that. I just finished teaching an AngularJS class yesterday.

ok, no more plugs.

Rich Freedman asks: So, how does the (new) view encapsulation work? I mean new since 1.x

Ken Rimple: OK, so view encapsulation

View Encapsulation is a built-in feature in Angular

(2.x +)

Every component has the ability to mount styles

there is a property in `@Component` that does it

example:

@Component({ selector: 'silly-component', styles: [` ul { font-weight: bold; } `] ... }) export class MySillyComponent() { ... }

When it mounts that component, it will automatically embed the styles, and add a unique identifier to the selector so that the style that modifies the `ul` in `silly-component` doesn’t leak out and kill every other UL with its boldness.

let me run this in a plunker and show you the output that it gives me

I’ll share the URL so you can see it LIVE! (cue the cheesy imitation)

hah, it’s not working yet – cue the Price is Right failure sound. Hang on.

ok

got it

here’s how it would look (I changed to a paragraph instead)

So, given:

@Component({ selector: 'my-app', styles: [` p { font-weight: bold; } `] template: ` <div> <h2>Hello {{name}}</h2> <p>Once</p> <p>Upon a time</p> <p>I could control my style!</p> </div> `, })...

It styles the component like this

<my-app _nghost-c0="" ng-version="4.3.1"> <div _ngcontent-c0=""> <h2 _ngcontent-c0="">Hello Angular! v4.3.1</h2> <p _ngcontent-c0="">Once</p> <p _ngcontent-c0="">Upon a time</p> <p _ngcontent-c0="">I could control my style!</p> </div> </my-app>

so, the host tag of the component, `my-app`, gets a style namespace of _nghost-c0

The content gets `_ngcontent-c0`

and so, because the original tag was just using a style of `p` but it was in the `styles` property of the component, it doesn’t bleed out into the global styles

so it cheats by adding a unique identifier

They send the css to the browser with the same thing

Now… You can control this.

There is a property called `encapsulation`

which is set to one of the enumerated constants in `ViewEncapsulation`

which are:

`ViewEncapsulation.Emulated` (default) – do this.

`ViewEncapsulation.Native` – use the Shadow DOM in Chrome to support this and in any other browser using Chrome’s rendering engine (don’t use this unless you want Chrome all the way)

and

`ViewEncapsulation.None` – don’t do it, don’t prefix, I want to hurt myself with a machete of my own code.

(I could make one of those of my code. I write too much code)

As you can probably tell, I have an odd sense of humor, made from the fires of keeping students awake in esoteric topics like these.

A groan is not a snore. +1 point.

Also I want to plug @richfreedman and his fantastic article on wiring up Angular to Spring Security.  Some of that has changed now with the introduction of the Http Interceptor in Angular 4.3.1, but it’s a great read nonetheless.

Ken Rimple says: You need to learn the concepts behind ECMASCript modules before you dive into Angular.

Specifically the whole `import { thing } from `npm-module-name` idea, and how module code is organized.

I wrote a pretty extensive article on how that works here

Because Angular does all of its dependency management through ES modules, you need to know it. Cold. It will save you from frustration.

You’ll learn it along the way, but you may want to save yourself some pain and scan this. Also, the Angular team introduced the Ahead of Time compilation process for building production-sized angular apps (read; compressing and dropping what you don’t use)

You can get a 5 or even 10 to 1 compressed JS size out of the production version of your app -vs- the dev version. But it comes with caveats. I go through that in that article.

Shaw Levin asks: What’s the proper way to incorporate LDAP (Windows) authentication into an Angular app hosted in IIS?

Ken Rimple: Ok my guesstimate on this

You’d need to install some sort of web interceptor / API that exposes the LDAP authentication from IIS. I have zero experience with those.

Now, on the Angular side, you’d either (depending on the Angular version) a) extend the HttpBackend (@richfreedman has done this) to watch and support intercepting the authentication error, or b) (4.3.1+ of Angular) use the new Interceptor to track the authentication event.

Angular can support writing / reading to cookies in the browser, or holding onto authentication tokens like Rich showed us in his blog article in JWT>

And now backing out of the way. The Honorable Rich, you may have the floor sirrah!

(but I am no expert here)

Rich Freedman: Thanks : -) My current client is doing this, but with CAS (ugh). But basically, there’s a an filter in the back-end app (Spring Boot), that forwards to CAS when you ask for the app, and then CAS redirects back.

As Ken said, we have an http interceptor that catches 401s and redirects to a url in the back-end app that will redirect to CAS [using 4.3.0 of Angular]

-30-
Juliana Reyes

Juliana Reyes was Technical.ly's editorial product lead after reporting on the Philadelphia tech scene for four years. She's co-president of the Asian American Journalists Association Philadelphia chapter and a two-time Philadelphia News Award winner for "Community Reporting of the Year." The Bryn Mawr College grad lives in West Philly, likes her food spicy and wears jumpsuits often.

Advertisement

Sign-up for regular updates from Technical.ly

Do NOT follow this link or you will be banned from the site!