Use DIV, TR, or any other tag instead of FORM tag in Angular 2

angular

I got this question in one of my tech Facebook groups today:

In Angular2, Is there anyway for dealing with forms rather than form tag??? As In AngularJS 1.x, there was <form> and <ng-form>.

Is there something like that in Angular2 or we must deal with form tag?!

And the answer is: Yes. It’s possible to create forms without the form tag in Angular 2, with a gotcha…

Here’s how:

Template Driven Forms

If you look for the selector for ngForm directive in Angular2, you’ll find it like that:

Note that last one. Any element with ngForm tag <ngForm ...> or attribute <any ngForm ... > should work.

Reference

Reactive Forms (Model Driven)

The selector for formGroup directive is:

Which also means that any element with formGroup attribute should work.

Reference

Gotcha

There is a relatively-big bug with non-form elements used as forms in Angular 2. The submit events do not work.

The implementation is just not as mature as Angular 1.

I have raised a bug here in March, but it’s probably a low priority:

@angular/angular#7807

You might be able to comment on it stating your scenario to bring it some attention.

How to use jQuery with Angular 2 in few easy steps with Angular CLI

1440764020jquery-logo1

Please do not take the post as an endorsement of using jQuery with Angular 2. I do not think it’s a good idea. Most stuff you use jQuery for cam be done directly from Angular 2.

However, there might be legitimate reasons for using jQuery, like using jQuery widgets and plugins that do not have a non-jQuery based equivalent. If you are facing that, try this guide:

If you are using the Angular CLI (my personal recommendation), you can use jQuery with Angular 2 in very few and easy steps as follows:

First: Install jQuery, the actual library

Then: Install jQuery TypeScript autocomplete

Finally: Go to the ./angular-cli.json file at the root of your Angular CLI project folder, and find the scripts: [] property, add this inside it:

(or use the slim version if that’s your cup of tea, keep the rest of the path as-is)

After that, jQuery will be available for you as a global variable. You can log jQuery’s version (which is available as jQuery.fn.jquery) to ensure it’s working brilliantly.

AngularConnect Videos & Free Angular 2 Router Book (Only for a few hours)

Hello,
This is Meligy from gurustop.net. I wanted to send you a very quick email to let you know about Angular 2 conference that took place in the last couple of days, Angular Connect.

The videos for the conference are already available on YouTube.

Check them out from here:

https://www.youtube.com/channel/UCzrskTiT_ObAk3xBkVxMz5g

There are videos for each whole-day track of the 2 tracks 2 day conference.
There are also videos for each session starting to come out. Seems all Day 1 is there, and Day 2 coming eventually.

For browsing through the whole-day videos, you can use the schedule page as guide, or just watch the individual session videos as they come out.

The sessions page on the site has all the separate videos that came out, and all the slides that are announced on Twitter, etc.

Another option is wait for the next message from me, as I’ll email you later all the most important summaries from the conference and what I think is must-watch.

Until then!


Meligy
gurustop.net
ng-sydney
Twitter | LinkedIn | StackOverflow

P.S.

This tweet was posted about 12 hours ago:

Victor is from the Angular Router team, and he writes the best Angular tutorials on
vsavkin.com.

Obviously this is only for less than 12 hours now, so get it quick.

Angular 2 final is released, here’s what you need to know

Update

The official release announcement is now out, with notes about future semantic versioning.

P. S. Sorry for spamming today with many emails. It won’t be the usual rate for these emails. I promise.

Hey,
Earlier today I sent you an email, saying that there’s a special Angular 2 event, where I expected the team to tell us when they are going to release Angular 2 final. I thought it would be too optimistic to ask for Angular 2 final today, but at least get a date!

I was wrong!

Watch the event stream, from the time 4:49s:
youtube.com/watch?v=xTIWBXkpvDc&t=4m49s

Yes, Angular 2 final is here. and it’s pretty much RC 7. No breaking changes :)
See the changelog as always.

Well, that’s it really. The NPM packages are updates, you just change the RC versions from 2.0.0-rc.7 to 2.0.0, and voila!

What About Angular1?

It will continue to be supported as long as the team sees a lot of usage (which they judge by how many people check the docs, now over a million people, 3 or 4 times Angular 2).

Most of the new minor features will be to make it more like Angular 2 though, and easier to migrate.

The Future

So, what comes after Angular 2 you ask?

Many small improvements that limit breaking changes, many more frequent releases to come without breaking your stuff.

One thing the team said is that they are not done making Angular faster yet, or smaller. They also said they really want to make the reactive / stream story amazing, and I’m guessing there’s still more work in the router space.

Then every 6 months or so (that’s February next year for the next one), a big release with breaking changes and semantic versioning, the next breaking-changes release, it will be Angular 3.

Most likely we’ll get the automatic project upgrade tool that the Angular team uses for automatic upgrades inside Google as well. The team said it should be by the time Angular 3 is out.

Very exciting, go check the whole special event video yourself!

I’ll be checking for more Angular2+ goodness, and emailing you with my findings as always.

Cheers,


Meligy
gurustop.net
ng-sydney
Twitter | LinkedIn | StackOverflow

Expecting Some Big News From The Angular 2 Team Today

Update 2:

Angular 2 final is here already!
Read my follow-up post here

 

Update 1:

Here’s the direct link to the livestream:
youtube.com/user/angularjs/live

The same YouTube channel will have the recording if you are checking this later.

Hello,
This is Meligy from gurustop.net. I thought I’d drop you a quick note to let you know that the Angular 2 team are having a local meetup in the mountain area in the U.S. later today, and they are saying it’s going to be a very special one.
It’s even titled Special Event!

What’s going to happen? Are they going to release Angular 2 Final?
That’s unlikely. But they might announce the release date!
Will it be in Angular Connect this month, or ng-europe next month?
I can’t wait to know!!

Well, the meetup is going to be streamed anyway. And it’s going to be in very convenient times for those living in the U.S. or Australia especially.

The talk will start at 7 PM PST, which is 12 PM East Australia Time, so you can watch in the evening, or during the lunch break, depending on where you are in the world!

Just check the Angular twitter account 10 minutes or so before the show start.
They should post the livestream link around then.

If you are into twitter, you can send them questions using the hashtag #ashng, but if you aren’t, you can just check the twitter page (no account needed) only for the streaming link.

In other news…

If you haven’t heard already, Angular 2 RC 7 has been released earlier this week.

The changelog shows only RXJS and Zone library upgrades, and a fix for lazy loading in the router when using Webpack.

Lazy loading is an interesting piece when it comes to play with NgModules and AOT compiler. Here are some great slides about what the Angular compiler does. We need to dedicate more time to the topic still.

If you want to take advantage of the fix, it should be a matter of upgrading your packages and nothing else. The team are keeping their promise to limit the breaking changes after RC 5 deprecations, and this is awesome!

Here’s how Angular-CLI upgrade commit looks like for example. Only package.json changes. Nothing else.

Speaking of the CLI, they also released a new version yesterday. You should check it out. The changelog tells you what’s new, but you can also directly check the commit log.

It should be a matter of npm i angular-cli@webpack. There’s now less need to work with the CLI from Github directly, but that’s how I personally tested the release yesterday even before it came out. I’m rewriting my guide on how to do it. Stay tuned!

That’s it!

Watch the meetup either streamed or recorded, or don’t worry about it as I’ll always keep you updated with any big news.

Until next one,

Cheers,


Meligy
gurustop.net
ng-sydney
Twitter | LinkedIn | StackOverflow

Learning Angular 2 recent RCs and future release plans

Hello there,
This is Meligy from gurustop.net. Today we are going to talk about the new things happening in the Angular 2 world.

Angular 2 RC 5 has been released a few days ago, and RC 6 is going to be out in a week or two. RC 6 will be mostly removing deprecated features. This sounds like deprecated forms, deprecated router, and support for bootstrapping Angular applications with components, as you should be using NgModules instead.

This means that, if you haven’t already, you should upgrade to RC 5, and change your code that’s using deprecated features before RC 6 is released. At least there’s a migration guide for that!

The good news though is that, beyond already deprecated stuff, the Angular team plans on avoiding breaking changes after RC 5 all the way to Angular 2 final release.

This means we might be still on track for a final release in September or October max! The ng-europe conference has been announced, and is scheduled for October 25 – who knows…

Of course this email is more about learning than about news. So, here are a few resources to lean all the new functionality in Angular 2. We’ll talk about the new forms module, and the new, 3rd router.

Forms

[Video] Latest Angular 2 Forms w/ Kara Erickson

Kara is an awesome lady from the Angular team itself, who has been working on the forms module for a while.

In this video she explains many features of the new forms module, and the 2 different programming styles it offers.

There’s also a nice written summary of the talk by Juri Strumpflohner, and the source code she shows in the talk is available here.

— Thoughtram Articles

Pascal Precht, an Angular Google Developer Expert (GDE, like Microsoft MVP), has a nice collection of Angular 2 articles on his company’s site, Thoughtram.

For forms, I suggest you check the posts in this order:

  1. Template-Driven Forms
  2. Reactive / Model-Driven Forms
  3. Custom Validators
  4. Custom Form Controls

— Template-Driven or Model-Driven?

Template driven forms are similar to forms in Angular 1. They use ngModel to connect to the data object, and HTML attributes like required etc. for validations.

Reactive / model driven forms require you to build an object representing your form structure in JavaScript (of course I actually mean TypeScript) – often referred to as the form model. Don’t confuse that with ngModel. By form model here we don’t mean not the actual data object that form control values are bound to, but an object that represents the form controls, validations, hierarchy, etc.

Angular 2 provides a convenient FormBuilder object that you use to create the form model. It also allows you to create things like ControlGroup (a fieldset / nested/child form, or even the top most form) and ControlArray (which contains controls in repeats with dynamic length).

Instead of connecting to ngModel, you connect your HTML inputs to the form model object you created via formControlName. Check the above links for the code samples.

Now that you know both, how do you choose?

Here: If you worked with Angular 1 for a bit, the template-driven model will feel natural to you. I suggest you start there.

After that, learn the reactive / model-driven style, and roll on with it.

The reactive model is what feels more natural in an Angular 2 world. Everything in there is based on RXJS like many other pieces of Angular 2 – including monitoring value change and even validation. If you ask me, I’d say you should consider this like the only forms model that ships with Angular 2.

By the way, the official documentation for forms isn’t bad at all. Here it for template-driven forms, and for reactive forms.

––

Now, we should talk about the router next, and the most important / most new piece, NgModels.

But, I look at this email, and think again…

There are a lot of links in this email already, and you need some time to check the each one of them…
So, I’ll give you a chance to do just that!

Let’s talk about routing, the Angular Ahead of Time (AoT) compiler, and NgModule together tomorrow. They actually make sense together anyway, as you’ll see.

 

Till then…

Have a good day,

 


Meligy
gurustop.net
follow me on twitter

How To Get jQuery To Work With Angular 2 CLI – Webpack Edition

angular-webpack

I wrote a post yesterday that talked about:
Using Webpack with Angular CLI directly from official Github source
The post seemed to get a bit of traction on twitter, and among other feedback, I got an interesting question in a direct message:

Hi Meligy, Have you tried importing jQuery in Angular-CLI webpack branch project anytime??

Well, turns out I didn’t. I expected it to be just a require(...) / import ... line away. With Webpack, you often don’t need much more than that.

But then when I tried, I found a problem after another, which turned to be very specific to jQuery. It’s an edge case, but for the library the community size of jQuery, it’s worth showing:

A Working Configuration

First, install jQuery:

Then install jQuery typings:

Adding a test

Then you can modify src/main.ts to include and test jQuery:

  • Add the import:

  • Change the bootstrap(AppComponent); line to:

Running it

You can go ahead and run ng serve or ng build -prod. I saw what looked like a TypeScript error in the output, so, go run just that:

You’ll get an error:

Explaining the problem

This error is because of a conflict between Angular Protractor and jQuery. Angular Protractor defines a global “$” that you use to write your Selenium element selectors nicer, etc. Normally you don’t write real jQuery code in a Selenium test, but Protractor is included in the TypeScript definitions that are included in the entire application.

Working around it

A temporary workaround is to manage the typings files for the website (src folder) and End To End tests (e2e folder) separately.

Each of the the folders have a typings.d.ts file that has (possibly among other things), a typings reference to the root level typings folder:

The problem is that the typings/index.d.ts file looks like:

Now, we can’t have both angular-protractor and jQuery in the same file, but we cannot modify typings/index.d.ts directly because every time we run typings install, the file will be overridden (and many even add the typings folder to .gitignore).

What we can do though, is replace the reference to it from src/typings.d.ts and e2e/typings.d.ts. When we do, we need to account for path change, we’ll need to prefix the paths with ../typings/ to point to their correct location.

In src/typings.d.ts, we replace the ../typings/index.d.ts reference line with:

In e2e/typings.d.ts, we replace the ../typings/index.d.ts reference line with:

And that should be it. No errors n TypeScript compilation, and running ng serve, then opening http://localhost:4200 shows us that the app still works, with the bootstrap() call now executed from jQuery’s ready call – which we added only to make sure it works!

Run ng build -prod and check the output in dist. You’ll find that it also works well.

Remember, this is only a workaround!

A drawback of what we did is that every time we add typings for a new library using the typings command, we’ll have to add a reference to it manually in src/typings.d.ts and/or e2e/typings.d.ts depending on fit. It’s easy to forget the manual step and get confused.

Luckily though, this is an edge case. Most of the libraries will not have such conflicts (see, that’s why everybody says modules are cool and globals are bad!). For most libraries, all you’ll need to do is to require(..) / import ... a module from the library, and everything will happen magically. Thanks to Webpack, you’ll not even need to setup vendor or systemjs config etc. Check my previous post for more information.

Other ideas

A few other starters seem to have the same problem. One other way to tackle it is to exclude the path typings/globals/angular-protractor from the Webpack config, but currently, I can’t see this config exposed from the Angular CLI. I’m sure it’ll be there once it’s final etc., but it’s not there now.

Another idea is to have a noConflict typings version of jQuery. There’s a pull request to DefinitelyTyped registry to include that, but it’s abandoned and closed at the moment. You can try calling the exact file via typings as a github~ file not dt~. But obviously you miss potential updates.

The best thing that can happen is that the Angular CLI would bring the separation of typings for src code and e2e tests built-in, which may or may not land in the CLI. Let’s see!

Should you use jQuery with Angular 2 at all?

I think the answer is: avoid it if you can.

I’m currently working with a team that has it included, and it was mostly due to needing some UI widgets that are only available for jQuery. I’m hoping that this is going to change with more UI widgets coming standalone, and easy to wrap in Angular 2 components / directives. Many widgets are becoming available with the Angular 2 wrappers already, like the lovely ng2-bootstrap collection.

Use Angular 2 CLI with Webpack Directly from Github Source Code

angular-webpack

You have heard the rumour, that Angular CLI is going Webpack. And it’s true. The CLi is replacing broccoli + systemjs with Webpack.

Update 1 (See Update 2 for latest)

The Webpack feature has landed in master GitHub branch!
It’s not on NPM yet (subscribe to my newsletter to get updated when it’s), and it’s in active development.
So, you might still find benefit in trying it out directly from GitHub sources.

Update 2

The Angular CLI has landed on NPM, but you need to call it in a special way:

If you installed Angular CLI before, go

Then to install the Webpack version:

Gotcha

When you run `ng new some-app`, and go inside it and run `ng serve`,
if you might get error like:

To solve this error, you can go to `package.json`, and change
`”angular-cli”: “^1.0.0-beta.11-webpack”,`
to `”angular-cli”: “1.0.0-beta.11-webpack”,`
(remove the `^` from the version)
Then run `npm install`. It should work after that!

You can also skip the initial NPM install using the param `–sn` (skip npm):

Then go fix the package.json file, and run npm install manually, so it only runs once.

Git or Npm?

Depending on how safe you want to go, you might find the master branch of the CLI often having features that are very interesting. This is always the case of course, but it’s more severe as the Webpack move in active as it’s now.

To check the difference, see the release change log vs the git commit log.

I’m not 100% sure of the exact reasons that convinced the team to go this way, but as an end user of the CLI, I expect a few benefits:

  • Easier inclusion of 3rd party dependencies in the build output.

    Instead of having to fiddle with vendor.js file and systemJS config, you just call require("dependency"); and be done with it; where dependency can come from local directory or NPM package, and can be any TypeScript / JavaScript file, or even a CSS / HTML / image file!

  • Easier tree-shaking

    Which means removing parts that are not used in your program from the build output. Angular is betting big on this (mostly via rollup.js library, but possibly via Google closure compiler in the future). Webpack has a few features built-in around this as well.

  • Easier (seamless) Webpack integration

    The current official Angular2 Webpack cookbook says you need to call require("some-name.component.html") in your component’s templateUrl, which is silly because it’s Webpack-only syntax.

    Having tried the Webpack version of the CLI, I’m happy to report that you don’t need to do that anymore.

How to use Angular CLI directly from Github?

So, now that we know why Webpack might be interesting to bring to the CLI, let’s talk about how you can try it even before it’s officially released. That’s if you feel adventurous and want to be on the bleeding edge of course!

Normally you install the Angular CLI npm package by calling:

Which makes the ng command available anywhere.

Instead, of that, you need to do this:

Here’s what this will do:

  • Clone Angular-Cli and checkout the webpack branch

    Note that the same method can be applied with the webpack branch where this feature originally landed.

    You just need to call git checkout Webpack (assuming a branch named “webpack”) before npm link.
    This should automatically track the remote webpack branch (as in origin/webpack) if you have a fairly recent version of git.

  • Use the package information in package.json file inside the repository to build and globally install angular-cli NPM package from the contents of the repository.

    To make sure this process succeeds, we installed all the dependencies the repo has. I’m not 100% sure this is needed, but to be safe.

Now when you run the command ng, it’ll come from the version you just downloaded via git. In the future, when you want to update this version you just:

Let’s use it!

Run:

If you try to run ng serve or something similar now, you’ll get an error. This is because ng new downloads a version of the angular-cli into the newly created folder. This is the online version available on NPM directory not the one you have offline, so we need to switch to it.

Ensure that you are inside the new folder created, and call:

Note the difference:

  • When we were inside the git repository and want to use as a global depdendency, we called npm link with no arguments.

  • When we were in a normal project folder, and wanted to replace the local folder version of the depdendency, we called npm link angular-cli, where angular-cli is the name of the package we globally linked before.

Easier Way

Linking can now happen automatically by changing your `ng new` command to:

After that, you should be able to run the application:

You’ll notice a new output that’s different from what you used to. This is webpack output.

The website will still be available at the usual port 4200. Go to Chrome and open http://localhost:4200 to see it. Modify the app component and see live reload working as usual.

Other things will work normally, like generating components, etc. Check the following command though:

If you look at the generated output in dist folder, you’ll realise that it’s slightly different due to removal of systemjs.

The size is still quite big at the time of writing though, but this is the area we expect to see more love going to before Angular 2’s final release.

That’s it

Let me know if you enjoyed this post. Say hi on twitter, and sign up to my article updates newsletter.

Bonus Content: Using jQuery

After this post got a bit popular, someone asked me about getting jQuery working with this setup, which showed a particular edge case around protractor and jQuery conflict. Although I wouldn’t generally recommend using jQuery and Angular 2, wrote about how to workaround this conflict, and how to get jQuery to work with Angular CLI and Wepack here.

How to use Angular 2 with ASP.NET 4.5+ / ASP.NET MVC 5

I got the following question in my ng-sydney AngularJS usergroup:

How to setup ng2 with Vs2015 for asp.net like mvc/web API?

While many blog posts answer the question for ASP .NET Core, very few answered it for ASP.NET 4.5 / ASP.NET MVC 5. So, here’s what I tried, and seemed to work.

Create a new project in Visual Studio

I found this online project template template Angular2 Mvc5 sample application, and it worked pretty well.

File -- New Project

Run the sample you get to see the output working.

Also, read the template page for workaround to potential issues with Node.

Upgrade the outcome

Unfortunately, the template only gives you Angular 2 RC1 work, with the deprecated router.

Luckily, it’s not too hard to upgrade it!

package.json

If you go to the official Angular quickstart, which you can reach by going to angular.io, and clicking “Get started”), you can find the package versions you need in 2 ways:

  1. Clicking “live example”, which takes you to the Plunker example page, you can get the latest versions of Angular 2 packages in the system.config.js file.
  2. Scrolling to Step 1 – b, which shows a package.json file you can just copy the dependencies section from.

Once you figure out the version numbers, you need to apply these to the package.json file in the root of the web project, here’s what the dependencies piece looks like for me, for Angular 2 RC 4:

Try running NPM from a command prompt, or go to Visual Studio output window and change “Show output from” to “bower/npm”. If you see errores complaining about a version not existing of some package, the message will tell you what versions are available, and then you can just pick the highest.

For example, I’m excluding replacing the deprecated router from this exercise. So I kept it, and it didn’t have a package for rc4. The error message about that told me that the max version available is rc2, and that seemed to work fine.

The new router also has its own version. You should be able to see that version in the config file like the other Angular files though.

Angular Forms

After that, since Angular forms became a separate module in RC3, this module was not included.

So, first you need to add it, it has a separate version as well. The plunker systemJS file will tell you what. And it’s shown in the above sample.

Then, you also need to add it into your own systemJS config file systemjs.config.js. Just add it to the packageNames definition. It should then look like:

And that’s it. Run the application again. You should still see the demo Todo-list with routing working.

Look at the browser devtools console. You should see a warning that you are using the deprecated forms module (what is available by default), and shows you a link of how to override it.

This means the project is working well with Angular 2 RC4, and the deprecated forms and router.

Cleanup

Next, you should be able to start deleting the sample components to leave for your own application components.

Before you do that, you might want to see how the project template works, including the serverside ASP.NET MVC bits. This will give you some guidance on how to structure your own.

Once you are done, you can remove the deprecated router from application bootstrapping file and from NPM dependencies. Then start using the new router, which we already included in the previous steps.

You should also be good to disable the deprecated forms (those are not a separate NPM module, so that stays the same), by modifying the application bootstrapping code as the link in the browser console tells you.

Good luck :)

Where’s Angular 2 going after a couple of RC releases?

Note

This blog post first appeared in my Web Developer Newsletter on June 16.
Look for the form to sign up to the newsletter below.

Hello!
This is Meligy from GuruStop.NET. Just checking if you got the news, Angular 2 RC2 is out!

Here’s the official announcement – and the changelog

The big highlights for this release for me seem to be:

  • The first release of the template compiler
    It allows you to compile templates as a build step, and avoid loading the Angular compiler in runtime.
    The Angular team say this compiler is the most essential to marking Angular 2 as final release.
  • Simplifications to forms
    If you played with Angular 2 forms and find the syntax confusing / redundant like me, this is big news
  • A new rewrite of the router
    This rewrite seems better than the on in previous RC.
    The official blog says it has contributions from ui-router and ngrx/router
  • Some new features
    Namely the animation framework

By the way, I’m personally sticking to Angular CLI when trying newer versions of Angular 2.
If you are taking this route, note that you need to uninstall the CLI, and clean npm cache before installing a new version.

That’s it for me. How about you?

Have you been playing with Angular 2 yet?

Or still looking for a good place to learn it?

Write back to me and let me know :)

Cheers,