Skip to main content

Components

Contents

Definition

  • Building blocks of the angular app.
  • Every component consists of three sections
    • TS file for logic
    • HTML file HTML template
    • CSS file styles for the template

@Component

TestComponent
    @Component({
selector : 'test',
templateUrl : './test.component.html',
styleUrls : ['./test.component.css']
})
  • selector defines html like tag we can use in pages
  • templateUrl defines path for html template
  • styleUrls defines css files to be use for the html template

HTML Template

  • Looks like a normal html but it is NOT
  • Syntax extended to allow
    • Custom component selectors <nav-bar></nav-bar>
    • Data binding {{ count }}
    • Directives *ngIf
  • Browser CANNOT understand bare template. It has to interpreted by angular framework first

Data binding

  • Interpolation
    • html {{ count }}
    • ts count : number = 5
  • Property Binding
    • <a [title] = "link_title">
  • Event Binding
    • <button (click) = "calculate()">
  • Two-Way Binding
    • <input [(ngModel)] = "userInput">

Read Data Binding Section

Directives

  • Structural Directives
    • *ngIf
    • *ngFor
    • `*ngSwitch
  • Attribute Directives
    • ngClass
    • ngStyle

Read Directives Section

Life Cycle of Components

Component has a life cycle managed by Angular and provides life cycle hooks to act when they occur

note

NOTE: Constructor() is called before ngOnInit()

Order:

  • Constructor()
  • ngOnChanges()
  • ngOnInit()
  • ngOnDestroy()

Input and Output

@Input

Child.TS
  @Input('count') public count: number;
Parent.HTML
  <div>
<child [count] = 5></child>
</div>
Child.HTML
  <div>
{{ count }}
</div>

@Output

Child.TS
  @Output('passCount') public countEmitter: EventEmitter<number> = new Emitter();
this.countEmitter.next(5);
Parent.HTML
  <div>
<child (passCount) = "receiveCount($event)"></child>
<p>{{ count }}</p>
</div>
Parent.TS
  count: number;
receiveCount(count: number){
this.count = count;
}

Read Component Communication Section