Key comparisons and changes from Angular 1 to Angular 2
Controllers vs Component
Let’s go over the most obvious change: how a Controller is now a Component and how it compares in Angular 2.
Controllers in Angular 1 HTML:
In Angular 2 we have something similar, we are declaring our class name “GameComponent” that is equivalent to the function “GameController” in Angular 1, and by using a decorator the @Component that describes the template (the HTML) and the name of the selector named ‘my-game’, the selector creates an HTML tag that will read the template and will be used in the HTML page.
Components in Angular 2 HTML:
Component in Typescript:
The second change is Bootstrapping Angular. In Angular 1 we needed to add the ng-app directive in our html tag or bodytag or anywhere needed to start the app, and then we told the name of the module we created.
In angular 2 we bootstrap with code, which we import from angular/platform-browser-dynamic, and then we import our component, and we call the bootstrap function to call the initial component that is the parent component of our entire application.
In Angular 1, to avoid repeating code a Service needed to be created, or a Factory or Providers or Constant, this created some sort of values that Angular would use across the application. In angular 2 we still have the same need, but these get all consolidated just inside a class.
In Angular 1 we could have a service like console service to get all the list of gaming consoles, where we register the Service as Game Service and create a function getConsoles that returns a list of Gaming consoles:
In Angular 2 we declare a class called GameService and has the same method get Consoles, the syntax is similar the big difference is we are looking ES5 on Angular 1 and Typescript on Angular 2:
In the previous example we created a service, and the way to Inject it in Angular 1 is to Register the service so we did this in this line of code, that works like a dictionary, we say the GameService is named this string “GameService.”
In Angular 2 we simply create a provider to this Component or any child of this Component so we do this just once per app:
So this is the difference of registering the service between Angular 1 and Angular 2, so once we register it, we need to get it and be able to use it . In Angular 1 we might have a controller that needs this service so we need to inject the service into the controller we use the $inject:
In Angular 2 the process is similar but instead of using strings, set the objects inside the constructor of the class, and we set it to a variable that we will be able to use
These were some basic examples of the main differences between Angular 1 and Angular 2 key components, services, controllers and new components and how to use them and set them.