Angular Cheat Sheet

Angular Cheat Sheet
Written by Sagar RabidasNovember 18, 2021
12 min read
Angular
2 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 2 VIEWS SHARE
Sagar Rabidas

Software Developer

In this blog, we will discuss on Angular Cheat Sheet.

Angular is a TypeScript based open-source web application framework used in building both web and mobile-based applications. In this article, we will go through some of the angular features by explaining some of its core APIs. You can follow this angular cheat sheet to build your project. We have tried to cover Angular CLI, Angular Lifecycle Hooks, Angular Routing, and much more here.

Angular CLI

Angular gives us the ability to do a whole lot using their CLI. You can config the entire application by just using the CLI. Here are some of the commands:

  • npm, install -g @angular/CLI: This command will install the Angular CLI into our local machine using npm.
  • ng new <application name>: This will set up a new Angular application using the ng new command.
  • ng new <application name> --prefix best: This creates a new project and sets the projects prefix to new.
  • ng new --help: This returns all available Angular command lists.
  • ng lint my-app: This command checks our entire application for any linting warnings.
  • ng lint my-app --fix: If there are any form of linting errors, this command will fix them.
  • ng lint my-app --format stylish: This formats our entire codebase.
  • ng lint my-app --help: This command returns all the available linting command lists.
  • ng add <package name>: This command will use your package manager to download new dependencies and update the project with configuration changes.
  • ng generate component <name>: This will create a new component of our application. We can also use the ng g c <name> shorthand to do this.
  • ng g d <directive name>: This command angular directive.
  • ng g s <service name>: Creates a new Javascript class-based service.
  • ng g p <pipe name>: Generates a new pipe
  • ng g cl <destination>: This will create a new class in the specified directory.
  • ng build: Builds the application for production and stores it in the dist directory.
  • ng serve -o: Serves the application by opening up the application in a browser using any port 4200 or any available port.
  • ng serve -SSL: serves the application using SSL

Angular Lifecycle Hooks

A component in Angular has a life-cycle, several different phases it goes through from birth to death. We can hook into those different phases to get some pretty fine-grained control of our application. Here you can see some Angular Lifecycle Hooks.

  • nonchanges: This is called whenever one of the input properties changes.
  • ngOnInit: This is called immediately after non-changes are completed and it is called once.
  • ngOnDestroy: Called before angular destroys a directive or component
  • ngDoCheck: Whenever a change detection is running, this is called.
  • ngAfterContentInit: Invoked after Angular performs any content projection into the component’s view.
  • ngAfterContentChecked: This is called each time the content of the given component has been checked by the change detection mechanism of Angular.
  • ngAfterViewInit This is called when the component’s view has been fully initialized.
  • ngAfterViewChecked: Invoked each time the view of the given component has been checked by the change detection mechanism of Angular.

How Angular Hooks are used

Always remember that hooks work in a component or directory, so use them in our component, we can do this:

blogpost

Component DOM

Angular comes with its DOM features where you can do a whole lot from the binding of data and defining dynamic styles. Let’s take a look at some features:

Before we dive into the features, a simple component.ts file is in this manner:

blogpost

Let's look at some template syntax:

  • Interpolation: using {{data to be displayed}} will display dynamic content from the ts file.
  • <button (click)="callMethod()" ... /> : Adding Click events to buttons to call a method defined in the ts file
  • <button *ngIf="loading" ... />: Adding Conditionals to elements. Conditionals have to listen to truthy or falsy value.
  • *ngFor="let item of items": iterate through a defined list of items. Picture this as a for a loop.
  • <div [ngClass]="{green: isTrue(), bold: itTrue()}"/>: Adding dynamic classes based on conditionals.
  • <div [ngStyle]="{'color': isTrue() ? '#bbb' : '#ccc'}"/>: Adding dynamic styles to template based on conditions

Component Communication

Passing data from one component to another can be a little bit tricky in Angular. You can pass data from child to parent, parent to parent, and between two unrelated components:

  • input(): This method helps To pass a value into the child components.
export class SampleComponent {
@Input() value: 'Some Data should go in here';
}

Child components are registered in parents component like this:

<child-component [value]="data"></child-component>
  • output(): This method Emits an event to the parent component. A bunch of data can be passed into the emitted event which makes it a medium of passing data from child to parent:

To Emit the event from the child component:

@Output() myEvent: EventEmitter < MyModel > = new EventEmitter();
calledEvt(item: MyModel) {
    this.myEvent.emit(item);
}

And then the parent component listens to that event:

<parent-component 
(myEvent)="callMethod()"></parent-component>

Angular Routing

Routing is another cool feature of Angular, with the Angular Routing system we can navigate through pages and even add route guards.

Component Routing: We can define routes in our application by defining the path and the component to be rendered:

const routes: Routes = [ 
  { path: 'home', component:HomeComponent }, 
  { path: 'blog/:id', component: BlogPostCompoent }, 
  { path: '**', component: PageNotFoundComponent } 
];

For routing to work, add this your app.module.ts file:

RouterModule.forRoot(routes)

There are situations whereby you want to keep track of what is happening in your routes, you can add this to enable tracing in your angular project:

RouterModule.forRoot(routes,{enableTracing:true})

To navigate through pages in Angular, we can use the router link the attribute which takes in the name of the component we are routing to:

<a routerLink="/home" routerLinkActive="active"> Crisis Center</a>

The routerLinkActive="active" will add an active class to the link when active.

Writing Route Guards

We can define a guard for route authentication. We can use the CanActivate class to do this:

class AlwaysAuthGuard implements CanActivate {        
        canActivate() {
                return true;
        }
}

To use this rote guard in our routes we can define it here:

const routes: Routes = [
  { path: 'home', component:HomeComponent },
  { path: 'blog/:id', component: BlogPostCompoent,canActivate: [AlwaysAuthGuard],  },
    { path: '**', component: PageNotFoundComponent }
];

Angular Services

Angular services come in handy when you can do things like handling HTTP requests and seeding of data on your application. They focus on presenting data and delegate data access to a service.

@Injectable()
export class MyService {
    public users: Users[];
    constructor() { }
    getAllUsers() {
        // some implementation
    }
}

To use this service in your component, import it using the import statement and then register it in the constructor

import MyService from '<path>'
constructor(private UserService: MyService) 

To make things easier, we can use this command to generate service in Angular

ng g s <service name>

angular
angularservices
angular routing
2 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 2 VIEWS SHARE
Was this blog helpful?
You must be Logged in to comment
Code Block
Techiio

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

facebooklinkdeintwitter

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Copyright techiio.com @2020 Kolkata, India
made with by Abhishek & Priyanka Jalan
Copyright techiio.com @2020
made with by Abhishek & Priyanka Jalan