Angular Architecture

Component File Structure

A Code Snippet

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

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

      constructor() { }

      @Output()
      pageRequested = new EventEmitter<number>();

      onChangePage(page: number): void {
        console.log("page " + page +  "clicked");
        this.pageRequested.emit(page);
      }
    }

Not a lot to discuss here since the class above is very similar to java. Just a couple key differences:

A tag for this component in HTML would look like: <app-header></app-header>

Template Variables

<app-page1 [hidden]="currentPage !==1"></app-page1> <app-page3 *ngIf="headerComponent.pageRequested === 3"></app-page3>

Component Interaction

Services and Dependency Injection

The Observer Design Pattern

  ngOnInit(): void {
  	// This will automatically update if the books array is changes.
    // Because it is a referenced variable
    this.books = this.dataService.books;
    // This will not update automatically if the books array changes.
    // It is a local variable.
    this.numBooksByMe = this.books.filter( it => it.author === 'Me' ).length;
  }
    this.dataService.bookAddedEvent.subscribe(
      // first var: the incoming data
      (newBook) => {
        if (newBook.author === 'Me') {
          this.numBooksByMe++;
        }
      },
      // second var: error handling
      (error) => {
        console.log('An error occurred:', error);
      },
      // Optional complete event always takes no parameters
      () => {
      	// complete event
      }
    );
@NgModule({
  declarations: [
    AppComponent,
    Page1Component,
    HeaderComponent,
    Page2Component,
    Page3Component,
    FooterComponent
  ],
  imports: [
    BrowserModule
  ],
  // When provided with <InterfaceName> use <ServiceName>
  providers: [ {provide : 'DataServiceInterface' , useClass : DataService} ],
  bootstrap: [AppComponent]
})
export class AppModule { }

A Note on .gitignore

By default, Github will exclude /node_modules in the .gitignore file. This is good because this folder can be very large, and the contents can be easily obtained when opening an Angular project. However, if using Continous Integration, the build will fail without these files. So including these files should be concidered if using a workflow which automatically deploys.


Revision #2
Created 16 April 2022 23:38:17 by Elkip
Updated 17 April 2022 01:31:42 by Elkip