DEV Community

Apiumhub
Apiumhub

Posted on • Originally published at apiumhub.com on

Learning Angular as a React Developer

As a front-end developer you always get asked whether you specialize in React or Angular. These two mainstream technologies have their strengths and weaknesses, and each is more appropriate depending on the project, but in this article we will not be discussing that. Recently, I started working in Angular and this is a quick cheat sheet for getting started in Angular as a React developer.

Creating a component in Angular

Let’s imagine we want to create a CustomButton component. When we create this component in React, it can look similar to this:

//imports

export const CustomButton = () => {
  const onClick= () => {}

  return (
<button 
        onClick={onClick}
            className=”button-class”>
         Click me
    </button>
  )
};
Enter fullscreen mode Exit fullscreen mode

Where we have the name of the component, its markup and the logic it can handle in a JSX – or TSX if we’re using typescript – extension file.

In Angular, to create the very same component we can use the command

ng generate component custom-button
Enter fullscreen mode Exit fullscreen mode

And it will create a folder with three files inside: custom-button.component.html, custom-button.component.scss and custom-button.component.ts. How does Angular handle these three files to use them as one component? The configuration of this component is in the .component.ts file. It has the @Component decorator that tells Angular how to process and instantiate the component and where to find each layer of information. This would be the same example as before in Angular:

//custom-button.component.html

<button
    class="button-class"
    (click)="onClick()">
    Click me
  </button>



//custom-button.component.ts
//imports 

@Component({
  selector: 'custom-button',
  templateUrl: './custom-button.component.html',
  styleUrls: ['custom-button.component.scss]
})
export class CustomButton {
  onClick = () => {}
}
Enter fullscreen mode Exit fullscreen mode

As you can see they look pretty similar but there are some noticeable syntax differences due to the fact that React uses JSX and Angular uses HTML for the markup:

  • In Angular classes are set by the attribute class
  • Angular components are visible in the browser inspector. In this example we would see something similar to this
<custom-button class=”button-class”><button>Click me</button><custom-button>
Enter fullscreen mode Exit fullscreen mode
  • Notice that Angular creates an additional layer in the markup that stands for the component itself while in react you would see the button directly

Adding attributes to a component

In React, we use props to make components customizable and dynamic. For example we might pass on the property text=”Click me” to make the button more generic:

export const CustomButton = ({text}) => {
  const onClick= () => {}

  return (
<button ...>
         {text}
    </button>
  )
};

Enter fullscreen mode Exit fullscreen mode

In Angular we need to use the decorator @Input() in our .ts file and initialise it:

@Component({
  selector: 'custom-button',
  templateUrl: './custom-button.component.html',
  styleUrls: ['custom-button.component.scss]
})
export class CustomButton {
  @Input() text = ‘’ //Note that it is mandatory to initialise it either here or in the class constructor
  onClick = () => {}
}

Enter fullscreen mode Exit fullscreen mode

And use the double braces in the html:

<button
    class="button-class"
    (click)="onClick()">
    {{ text }}
  </button>

Enter fullscreen mode Exit fullscreen mode

Calling a parent component function

When using a purely UI component we might want to pass a function from the parent component to the child component. In React it would look something like this in the child component:

export const CustomButton = ({onClick}) => {
  handleClick = () => {
    //some internal logic
    onClick();//function passed from the parent component
  }

  return (
<button 
        onClick={handleClick}
            className=”button-class”>
         Click me
    </button>
  )
};

Enter fullscreen mode Exit fullscreen mode

In Angular we would use the @Output() decorator:

@Component({
  selector: 'custom-button',
  templateUrl: './custom-button.component.html',
  styleUrls: ['custom-button.component.scss]
})
export class CustomButton {
  @Output() onClick: new EventEmitter<any>();

  handleClick = () => {
    //some logic
    this.onClick.emit()//here we can also pass the event or other data that we want to receive in the parent component
  }
}

Enter fullscreen mode Exit fullscreen mode

Creating an NgModule

We now know a bit on how to create an Angular component, but where does it live in the ecosystem of Angular? When we create a component in Angular, it needs to be declared in an NgModule. An NgModule is a block of code that has its own configuration, its routing and its dependencies specified with the @NgModule decorator, which can be lazy loaded by route. This may sound a bit tricky at first when you come from React, but let’s see it with an example. When we start an Angular project, it comes with a module called app.module.ts that contains the basics:

// imports

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Enter fullscreen mode Exit fullscreen mode

This is the most basic ngModule:

  • The declarations array indicates what presentation components it will include, for example if we are loading our custom button in this module we would include it here.
  • Imports: modules that are needed to load the current module. Internally Angular is adding the list of modules’ service providers to the application root injector. In this case, the BrowserModule has browser-specific services such as DOM rendering, sanitization, and location.
  • Providers: list of service dependencies that the current module has. This could be a service that loads data or a service that handles authentication for example.
  • Exports: not showing up here but it’s an array where you might export components of the current module to be able to use them in other modules.
  • Bootstrap: it’s the root component where Angular will insert in index.html.

Why do we need these modules?

Applications are always divided into functional blocks for maintainability. In React this division is up to the developers and there is no specific convention to follow, but in Angular the code can be divided into ngModules. The @ngModule decorator specifies the configuration of these parts of code, which includes its external dependencies, how its internal dependencies should be injected and how it should be compiled. This creates cohesive blocks of code with their own UI components and routing.

Not all modules are going to be presentational components to be shown by route. One example of a non-presentational component built-in module is the RouterModule, which is a heavily used module that Angular offers to define the existing routes and which components they should load. It allows you to track whether the current page corresponds to a specific route (RouterActiveLink) or whether a url needs some condition to be accessed (CanActivate).

The Angular team is also working on simplifying this configuration to eventually remove the need of an ngModule and do this configuration by route, we will discuss it in the next section.

New APIs to reduce the need of NgModules

In order to improve tree-shaking and reduce complexity, angular is working on creating new APIs where:

  • Dependency injection would be handled with providers and providers arrays directly. Instead of configuring the angular router via RouterModule.forRoot(routes, config) in the ngModule, it could be configured in the router.
  • Bootstrapping – which is currently configured in the ngmodule – would be handled by a new bootstrapApplication function.
  • importProvidersFrom function would allow compatibility with former ngModules.
  • Lazy loading components would be possible not only for ngModules but by individual components and children routes.
  • The dependencies of the each route could be specified individually instead of by module.

Next steps

Since Angular is a framework, it offers many more functionalities than React, such as the handling of forms, the routing, the requests handling and so, on which would be very interesting to explore next if you’d like to learn more about Angular.

As a React developer, learning Angular has given me the perspective of understanding how each technology tackles a specific problem and solves it, and it also helps to better understand the foundations of Javascript.

Discussion (0)