Select Page

Learning Angular as a React Developer

Lijie Ye
Published: November 24, 2022

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. I am currently working at Apiumhub, and recently I started working in Angular. 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>
  )
};

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 a typescript–extension file.

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

ng generate component custom-button

The command above will create a folder with three files inside:  ustom-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 = () => {}
}

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>

  • 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>
  )
};

In Angular, we need to use the decorator @Input() in our .ts file and initialize 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 = () => {}
}

And use the double braces in the HTML:

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

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>
  )
};

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
  }
}

Creating an NgModule

We now know a bit about 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 the 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 {}

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: 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; however, 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 for an NgModule and do this configuration by route, we will discuss it in the next section.

New APIs to Reduce the Need of NgModules

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 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.

Source: dzone.com