Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modified version of [this](https://github.com/akash-coded/mern/discussions/197) task in MERN for Angular. #164

Open
imwirelesscloud opened this issue Sep 17, 2023 · 0 comments

Comments

@imwirelesscloud
Copy link

Modified version of this task in MERN for Angular.
Let's create the equivalent UI/UX of the React app using Angular. I'll be thorough in breaking down the process for those who might need a refresher on Angular concepts.

1. Setting up a New Angular Project:

1.1. Installation:
To begin, you need the Angular CLI (Command Line Interface) installed globally.

npm install -g @angular/cli

1.2. Create New Project:

ng new angular-user-app

This command initializes a new Angular project. The CLI will ask if you want to add Angular routing (choose "Yes") and which stylesheets to use (choose "CSS" for our case).

2. Understanding the Project Structure:

Once the project setup is complete, navigate to the project directory (cd angular-user-app). The core of your app will reside in the /src/app directory.

  • app.module.ts: This is the root module, and it tells Angular how to assemble the application. Any new components, services, or other modules will need to be imported and declared here.

  • app.component.ts: This is the root component. All other components nest under this one. Its view (HTML) and styling (CSS) are linked through corresponding files: app.component.html and app.component.css.

3. Creating Components:

We'll replicate the User component and the UserList component.

3.1. User Component:

To generate the user component, run:

ng generate component user

or the shorthand:

ng g c user

This command creates a new directory user with four files.

  • user.component.ts: This is the TypeScript class for the component. Any logic for the component goes here.

  • user.component.html: This is the template/view for the component.

  • user.component.css: Any styles specific to this component.

  • user.component.spec.ts: Test file for the component.

Explaination: In Angular, components are a unit of UI. They consist of a class that handles data and functionality, an HTML template that determines the UI, and styles that define the look.

3.2. UserList Component:

Repeat the process:

ng g c userList

4. Data Binding & Directives:

Angular supports powerful data-binding features.

  • Interpolation {{ }}: Display a component's property in the view.

  • Property Binding [property]="value": Bind a property to a DOM property.

  • Event Binding (event)="expression": Execute an expression when an event occurs.

For our user list, we can utilize Angular's *ngFor directive to loop through the users and display them.

In userList.component.html:

<div *ngFor="let user of users">
  <app-user [userData]="user"></app-user>
</div>

Explaination: The *ngFor directive is a repeater directive. It instantiates the template for each item in a collection. The app-user is the selector for the User component, and we're passing data to it via property binding.

5. Input & Output:

To send data from the parent userList component to the child user component, use @Input(). Similarly, to send data from the child to the parent, use @Output() and EventEmitter.

In user.component.ts:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent {

  @Input() userData: any;

  constructor() { }

}

Explanation: @Input() indicates that the property value passes in from the component's parent, in this case, the userList component.

6. Services & Dependency Injection:

For fetching user data, it's a good practice to use a service.

Generate a user service:

ng g s user

Now, in user.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  private apiUrl = 'https://reqres.in/api/users';

  constructor(private http: HttpClient) { }

  getUsers() {
    return this.http.get(this.apiUrl);
  }
}

Explanation: Services are a great way to share information among classes that don't know each other. We're using the HTTPClient module to make API calls. This module needs to be imported in app.module.ts:

In app.module.ts:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    // components here
  ],
  imports: [
    BrowserModule,
    HttpClientModule,  // Add this line
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

7. Styling:

Angular scopes the styles to the component, ensuring that styles don't leak to other parts of the application. For global styles, use styles.css in the root.

For our user component, user.component.css might look something like:

.card {
  border: 1px solid #e0e0e0;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 2px 2px 12px rgba(0, 0, 0, 0.1);
}

The CSS here creates a simple card design which is popular in modern UIs.

8. Final Touches:

In Angular, you'll also handle routing (for navigating between different components), forms (for user input), and other advanced features like guards, lazy-loading, and interceptors, based on the complexity of the app.

For this exercise, since we've built a simple frontend, the above steps should have your Angular app up and running in a way similar to the React app we discussed earlier. Make sure to test the app regularly using ng serve to view the app in your browser.

Remember, the key difference between React and Angular is that while React is a library focused on UI, Angular is a full-fledged MVC framework. The methodologies are different, but the underlying principles of component-based architecture, state management, and modularity remain largely the same.


Continuing from where we left off:

9. Routing in Angular:

To create a Single Page Application (SPA) feel, Angular has a powerful routing system.

9.1. Setting Up Routes:

Inside the app-routing.module.ts:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { UserListComponent } from './user-list/user-list.component';

const routes: Routes = [
  { path: '', redirectTo: '/users', pathMatch: 'full' },
  { path: 'users', component: UserListComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Explanation: Here, we're redirecting the default '' route to '/users', which will display the UserListComponent. The RouterModule is Angular's way to handle frontend routing.

9.2. Displaying Routed Views:

In app.component.html, use the <router-outlet> directive:

<router-outlet></router-outlet>

This directive acts as a placeholder where the routed component will be displayed.

10. Implementing State Management:

While our application is simple, for larger applications, handling state can become complex. Angular has a state management library called NgRx which uses the Redux pattern.

Explanation: State management ensures that the state of your application is predictable and can be easily maintained, updated, or even debugged. It's useful when different parts of the app need access to the same data.

11. Forms in Angular:

Forms are essential for user input. Angular offers two approaches: Template-driven and Reactive.

For simplicity, let's use Template-driven forms:

11.1. Setting Up a Template-driven Form:

First, import FormsModule from @angular/forms in the app.module.ts:

import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    FormsModule,
    // other modules
  ],
  // declarations, providers, etc.
})

Now, you can use forms and the ngModel directive for two-way data binding.

12. Enhancing the UI with Angular Material:

Angular Material provides high-quality UI components.

12.1. Installation:

ng add @angular/material

12.2. Using a Component:

First, import the desired module in app.module.ts:

import { MatCardModule } from '@angular/material/card';

@NgModule({
  imports: [
    MatCardModule,
    // other modules
  ],
  // declarations, providers, etc.
})

In the component template, you can now use Material's card component:

<mat-card>
  User Data Here
</mat-card>

Explanation: Angular Material components are well-designed, adhere to Google's Material Design specifications, and integrate seamlessly with Angular applications.

13. Final Testing and Optimization:

Before deployment, always run tests and optimize:

ng test

This command will run unit tests specified in .spec files using Karma and Jasmine.

For end-to-end tests:

ng e2e

This command will use Protractor for e2e tests, ensuring the entire app works as expected.

Explanation: Testing is crucial for any application. Unit tests focus on isolated parts, while end-to-end tests consider the app as a whole.

Wrapping Up:

By following these steps, you should have a working Angular version of the previous React app. Angular provides robust tools and has a steep learning curve, but its power and flexibility are evident, especially in larger applications. Remember to consult Angular's official documentation for any advanced features or further clarifications.

Originally posted by @akash-coded in #162

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant