Ninja Space Content Blog

Week Five of Learning Angular

April 11, 2021
Depending on where I am in the tutorial, I think I may decide to either make Sunday the beginning of a new week or the ending of the current week. I am now getting into forms using the Programming with Mosh's Angular Tutorial. It seems like the right way to start a new week so all of the my notes about creating Angular forms could be in one place. Therefore, starting today, I'm in my 5th week of learning Angular. Click here to see my weekly breakdown of learning Angular.
 

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.
 

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. Most recently, I decided to complete a JavaScript coding bootcamp and graduated in Dec 2020.
Note: links to resources and promoting special deals may allow me to earn a small commission from each sale.