Ninja Space Content Tech Blog

Week Four of Learning Angular

April 5, 2021
I'm on week 4 of learning Angular now! To see my weekly break down on learning Angular, go to Angular Blogs' List. What I'm realizing is that because I am note taking and coding along the way, a 5 minute video tutorial could easily have me spending 15 minutes to digest the material before moving onto the next video clip! If there is an unforeseen bug, it would take even longer. So make sure you allot enough time in between if you're studying the same way I am.

Using ng-content property
Use ng-content container as mark-up convenience like so:
<div class="panel-body">
    <ng-content select=".body"></ng-content>
</div>

Directives
Use ngIf for looping depending on a condition. We use directives to modify the DOM. There are two types: structural and attribute. Other directives include: ngSwitchCase and ngFor. One way is:  

<div *ngif="courses.length > 0">
  List of courses
<div *ngif="courses.length == 0">No courses yet

 Another way is:  

<div *ngIf="courses.length > 0; then coursesList else noCourses">
    List of courses
</div>
<ng-template #coursesList>
    List of Courses
</ng-template>
<ng-template #noCourses>No courses yet</ng-template>

You can also use the hidden property as well but this doesn't remove the elements from the DOM; it just hides it. Example of a hidden property:
<div [hidden]="courses.length == 0">List of courses</div>
<div [hidden]="courses.length > 0">No courses yet</div>

ngSwitchCase
I really like the ngSwitchCase directive. It's great for switching things back and forth for viewing. Here is the sample code:  
<div [ngSwitch]="viewMode">
    <div *ngSwitchCase="'map'">Map View Content</div>
    <div *ngSwitchCase="'list'">List View Content</div>
    <div *ngSwitchDefault>Otherwise</div>
</div>

Important Note
One thing that threw me off that's different from React is you need a comma after the last object in your array in Angular or else you get a compile error. This is the correct syntax below:  list = [
    {id: 1,name: "course1"},
    {id: 2,name: "course2"},
    {id: 3,name: "course3"},
   ];

ngFor Directive useful values
ngFor is really ngForOf. You can utilize other things in this loop like:  index as i (local variable), first, last, even and odd.

Ex: 
<ul>
    <li *ngFor="let course of courses; even as isEven">
       {{course.name}} <span *ngIf="isEven">(EVEN)</span>
    </li>
</ul>

Remove and Update on Change Detection
Angular is so intuitive. It can detect change and updates automatically. It is so easily to create a remove button for each element like so: 

Under ts file: 
  onRemove(course: any) {
     let index = this.courses.indexOf(course);
     this.courses.splice(index, 1)
   }

Under html file:
<ul>
    <li *ngFor="let course of courses; even as isEven">
       {{course.name}} 
       <button (click)="onRemove(course)">remove</button>
    </li>
</ul>


TrackBy
TrackBy is such a great tool to use when you want to improve performance with large data. Here's an example.
Under ts file:

  trackCourse(index: number, course: any) {
    return course? course.id : undefined;
   }

Under html file:
<button (click)="loadCourses()">Add</button>
<ul>
    <li *ngFor="let course of courses; trackBy: trackCourse">
       {{course.name}} 
      
    </li>
</ul>

Example of an Attribute Directive using ngClass
There's usually more than one way of making something work. Here an example of using a favorite icon with an attribute directive:
<span
    class="bi"
    [ngClass]="{
        'bi-star-fill': isSelected,
        'bi-star': !isSelected

    }"
    (click)="onClick()"
    >
    Star Test Icon
</span>

Styling with CSS
You can style like so:

<button 
    [style.backgroundColor]="canSave ? 'blue': 'gray'"
    [style.color]="canSave ? 'white' : 'black'"
    [style.fontWeight]="canSave ? 'bold' : 'normal'"
>
Save
</button> 

or use ngStyle directive to make it look cleaner like so:

<button 
    [ngStyle]="{
        'backgroundColor': canSave? 'blue': 'gray',
        'color' : canSave? 'pink' : 'black'
    }"
    >
Save
</button> 

Safe Traversal Operator
This is important to use when using complex data. When a value is null, you don't want the console to throw red errors. By solving this , you can use the safe traversal operator with a question mark like so: 

<div>
<span>{{task.assignee?.name}}</span>
</div>

Custom Directives

To create a new directive, go to terminal and type: ng g d directive-name
 

Week Three of Learning Angular

April 1, 2021
I'm on Week Three of Angular and I'm going to re-do a workshop again because I wanted to figure something out that wasn't working properly for me before. I'm coding along with Programming with Mosh's tutorial on Angular.

My Fixes
In the Section 14-Solution-Favorite-Component, Mosh wrote the following line in the favorite.component.ts file: isFavorite: boolean; and it showed a red squiggly line for me and my front end would not compile right. There were two different changes that I could choose in order to fix it. I could either declare the state as false like so: isFavorite = false; or I could add the exclamation point after my variable name like so: isFavorite!: boolean;. The reasoning why it worked for Mosh his way and not for me is because I am using a later version of TypeScript. His tutorial is a few years old. That is something you'll always have to keep in mind as a programmer. Things are always changing.

Component API
This is where the input is the state and the output is the event. You would need to import the Input decorator and also note  @Input() isFavorite!: boolean; in your variable to define an Input property.

Output Properties
For some reason, I had to go over this twice to get it to work. Just like the input part, I had to import Output and additionally, also import EventEmitter and to define the output I had to code the following:  @Output() change = new EventEmitter(); and then add the following as a method: onClick() { this.isTest = !this.isTest; this.change.emit(); } and then finally, in the html file I could implement this like so: <favorite [isfavorite]="post.isFavorite" (change)="onFavoriteChange()"></favorite>

Styles
There are three ways to style. What comes last will become effective. You can write in-line with a style tag. You can use styles through the component.css or add styles property in an array. There's a reference on Shadow DOM.
 

Week Two of Learning Angular Part 2

March 25, 2021
This is Week Two of Angular Part 2, click here to see Week Two of Angular Part 1.

What else impresses me about Angular so far
I am so excited about their pipes and how easily it is to change the format of your data!

Two-way Binding
Following the Angular Tutorial from Programming with Mosh, I kept getting the following error: "NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'." After some googling, I realized that with my version of Angular installed, I had to go to my app.module.ts file to add:
import { FormsModule } from '@angular/forms'; and include FormsModule under my array of imports.

Using Bootstrap Icons
First, npm i bootstrap-icons. Then add @import "~bootstrap-icons/font/bootstrap-icons.css"; to the style.css file. After that, you can implement the icon of your choice from https://icons.getbootstrap.com.

Creating a New Pipe
You can create a new pipe in the terminal by typing ng g p pipe-name. Go to that ts file and edit the transform section. Then, in the template or html file, you will implement it.

Input Properties
Going through the lesson with Mosh at 15%, I couldn't replicate the same results as he did using the same code. It could be that my Angular/TypeScript version is different than his and so the implementation may be different now. I'll need to revisit this!

Cool Tip
A cool tip that I learned is how to change a variable name and let it change the rest of them by selecting the variable name, click F2 and then change the variable name and click 'enter'.
 

Week Two of Learning Angular Part 1

March 22, 2021
I'm officially on my Week Two of Learning Angular. Click here to see Week One. I'm finding that as I'm noting all of these while I'm learning, it's helping me immensely and I hope it'll help you. I decided to purchase Mosh's Angular Tutorial for $15. It seems like a great deal for 30 hours of tutorial and I don't have to waste time weeding through materials and watching in between ads from Youtube.

Components
To make a class a component, you have to add the decorator at the top like import {Component} from '@angular/core';

Then, apply it to the class like a function called a decorator function like @Component({
selector: 'names',
template: '<h2>Names</h2>'
})

You can name the selector anything you want here as this is where you define this name. Make sure to add a template. Then, you go to app.modules file and add the new class Component to the top. Then go to the html file and add <names></name> and you'll see the template on the page.

Instead of manually adding a new file name for a component, you can use the command line to create it as that will save you a few steps. For example, if you're creating a new component for dogs, it would be ng g c dogs that you'd type in the command line.

Directives
Directives are really powerful to use in the template: section. You can put in a loop like so:
<li *ngFor="let name of names">
{{name}}
</li>


Property Binding
There are two ways to use display data in the DOM. You can use interpolation like:
<h2>{{ title }}</h2> or Property Binding like:
<h2 [textContent]="title"></h2>


Bootstrap CSS Library with Angular
You can use boostrap library with Angular. First, in the terminal, you type the following:
npm install bootstrap --save. Then, go to styles.css to import it by adding the following to the top:
@import "~bootstrap/dist/css/bootstrap.css"; 

Event Binding
There was a bug that I kept getting. When I added a $event as a parameter, I kept getting this error: "Parameter '$event' implicitly has an 'any' type.ts(7006)" and after some digging around in StackOverflow, I found that it was because I had to specify what my $event type is so I had to add a : any like so: onSave($event:any) {console.log("Button was clicked info", $event)}

Template Variable
You can use hash in your input to create a variable like so:
<input #name (keyup.enter)="onKeyUp(email.value)" />

More Helpful List of Commands
  • To create a service in the terminal type: ng g s friends
  • To create a component in the terminal type: ng g c authors
This ends Week Two, Part 1. Continue on to Week Two of Angular, Part 2.
 

Week One of Learning Angular

March 20, 2021
I decided to start learning Angular and TypeScript this week. I looked at a 2 hour YouTube video by Programming with Mosh to get a good glimpse at it before I started practicing along. After looking at the video in normal speed for 2 hours (I would speed it up if I am going over it again), without getting my hands in code on VSC, I was really intimidated by my first tutorial on Angular. However, it also reminded me of Java, using interfaces, classes and constructors. Besides for looking at a couple Java YouTube tutorial videos last month, I haven't started a project with Java yet because I had a really intense month of trying to go over computer science materials for a series of interviews that I had to prepare for. I really need to get back to Java again when I have a chance but for now, I am going to continue with my learning in Angular.

Many local companies in my area are looking for developers who are knowledgeable in Angular, not React, so I'm going to build a couple of projects in Angular this summer for my portfolio. As I'm studying and learning, I'm going to document some notes week-by-week here on my Ninja Space Content blog.

Do I like Angular or React better after 1 week of Learning?
Even though I've only been learning Angular and TypeScript for a week, I can already see how powerful Angular is as it catches my errors and mistakes right away as I'm typing. It catches errors at compile time and doesn't have to wait until run time.

A data type that I need to get more familiar with is enum and it's a pretty useful tool to use as a data type. An example of how to use enum is the following: 

enum Name { Ninja = 0, Space = 1, Content = 2 };
let blogName = Name.Ninja;



Here's a Helpful List of Commands for a Mac 
I'm going to use this list as a reference and hope you'll find it helpful too.
  • If you already have Node, to install Angular on your Mac for the first time, use command: sudo npm install -g @angular/cli
  • type: ng --version in your terminal to see that version of your angular that you've just downloaded
  • Create a new Angular project by typing: ng new project-name in your terminal. Replace project-name with whatever name you'd like to name your file.
  • ng serve in terminal to open Development Server. Default is localhost:4200.
  • To install TypeScript onto your Mac computer, use command: sudo npm install -g typescript and to check your version, type: tsc --version
  • To compile, type: tsc main.ts or whatever your file name is and this will compile to ES5 main.js (js file) of your original file
  • Type: ng serve to transpile the code.
  • To run code, type: node main.js or whatever your file name is. This will let you see the console.log of your code.
  • Type: tsc *.ts --target ES5 && node main.js when getting an error that says "Accessors are only available when targeting ECMAScript 5 and higher.
Type Assertion
Something new for me that I learned is using Type Assertions to see my intellisense. There are two ways to do this. Here are the 2 examples.

let message;
message = 'ohayou';
let endsWithU = (<string>message).endsWith('u');
let anotherWay = (message as string).endsWith('u');


Interfaces vs. Classes
Interfaces are only used for declaration and not implementation. Classes are used for both variable declarations and implementations like functions.

Access Modifiers
Fields, properties and methods can be labeled with access modifiers like public, private or protected.

Properties
Properties split the methods like so in a class:
get X() {
return this.x;
}


Click here to read my Week Two of Learning Angular
 

About Ninja Space Content


Ninja Space Content I have been building simple websites on my own since 2008 and currently run several websites at the moment, including this one. I used to be an account manager for an affiliate/e-commerce company, helping affiliates grow their sales so I have some knowledge on the business side and client side of affiliate marketing. During the Covid-19 pandemic, I completed a JavaScript coding bootcamp and graduated in Dec 2020. I've been working as a contractor for a few software companies ever since.
Note: links to resources and promoting special deals may allow me to earn a small commission from each sale.