Angular

Last Updated: 6/15/2023

Creating Components

Use a Component

  • Create a component
  • Register it in a module
  • Add an element in HTML markup

Create a component

  • Create a file courses.component.ts under src/app folder
  • For multiple words use course-form.component.ts
  • Create a class and add export keyword to access outside
  • Pascal naming convention and Suffix with Component
courses.component.ts
export class CoursesComponent{}

course-form.component.ts
export class CourseFormComponent{}
  • To make it a component, add metadata that angular understands. We use decorator function to achieve this.
  • In Angular we have a decorator called component and attach to the class to make it a component
  • From angular import the decorator component and attach to the class
import {Component} from '@angular/core'

@Component({
	selector: 'courses',
	template: '<h2>Courses</h2>'
})
export class CoursesComponent{}
  • To component decorator function pass an object with 1 or more properties to tell angular how the component works
  • selector: css selector
    • courses for element <courses></courses>
    • .courses for class <div class="courses">
    • #courses for id <div id="courses">
  • With components we can extend html vocabulary
  • template: html template inline or in separate file

Register in app module

  • AppModule is decorated with NgModule decorator function

  • In declarations add all components that are part of this module

  • AppComponent is part of the AppModule

  • In app.module.ts import component and add it in declarations of NgModule decorator

import {CoursesComponent} from './courses.component'
@NgModule({
	declarations: [CoursesComponent]
})

Use the component

  • add it to the root component app.component.html <courses></courses>
  • Angular renders the template of the course component

Extensions

  • Auto import 1.2.2 by steoates

Creating Component using CLI

  • If the component is not registered in the module, angular will throw error - not a known element
  • In VS Code ctrl+` to open the terminal
ng generate component course
or
ng g c course

To skip test file
ng g c course --spec false //old version
ng g c course --skipTests=true
  • Creates a new component in the folder src/app