MSSE SENG 5199

Course Materials for the MSSE Web Application Development Course

slidenumbers: true

Angular Templates

Marc Kapke

kapkema@gmail.com


Templates


Template example

<h2>Article List</h2>
<p><i>Pick an article from the list</i></p>
<ul>
  <li *ngFor="let article of articles" (click)="selectArticle(article)">
    
  </li>
</ul>
<article-detail *ngIf="selectedArticle" [article]="selectedArticle"></article-detail>


Template syntax


Template expressions


Expression context


Expression operators


Expression guidelines


Data binding refresher


Interpolation


Property Binding


Event Binding


Two way Binding


Additional Binding scenarios


Attribute Binding

<table border=1>
  <!--  expression calculates colspan=2 -->
  <tr><td [attr.colspan]="1 + 1">One-Two</td></tr>

  <!-- ERROR: There is no `colspan` property to set!
    <tr><td colspan="1">Three-Four</td></tr>
  -->

  <tr><td>Five</td><td>Six</td></tr>
</table>

Class binding

<!-- reset/override all class names with a binding  -->
<div class="bad curly special"
     [class]="badCurly">Bad curly</div>

Class binding - toggle

<!-- toggle the "special" class on/off with a property -->
<div [class.special]="isSpecial">The class binding is special</div>

<!-- binding to `class.special` trumps the class attribute -->
<div class="special"
     [class.special]="!isSpecial">This one is not so special</div>

Style binding

<button [style.font-size.em]="isSpecial ? 3 : 1" >Big</button>
<button [style.font-size.%]="!isSpecial ? 150 : 50" >Small</button>


Built-in Attribute directives


NgClass

// CSS classes: added/removed per current state of component properties
  this.currentClasses =  {
    saveable: this.canSave,
    modified: !this.isUnchanged,
    special:  this.isSpecial
  };
<div [ngClass]="currentClasses">Some div</div>

NgStyle

// CSS styles: set per current state of component properties
  this.currentStyles = {
    'font-style':  this.canSave      ? 'italic' : 'normal',
    'font-weight': !this.isUnchanged ? 'bold'   : 'normal',
    'font-size':   this.isSpecial    ? '24px'   : '12px'
  };
<div [ngStyle]="currentStyles">
  This div is initially italic, normal weight, and extra large (24px).
</div>

ngModel

<input [(ngModel)]="currentHero.name">

ngModel

<input
  [ngModel]="currentHero.name"
  (ngModelChange)="setUppercaseName($event)">

Built-in Structural directives


*ngIf

<div *ngIf="isActive">Am I in the Dom?</div>
<!-- show/hide -->
<div [style.display]="isSpecial ? 'block' : 'none'">Show with style</div>
<div [style.display]="isSpecial ? 'none'  : 'block'">Hide with style</div>

*ngFor

<div *ngFor="let article of articles; let i=index">Article:  - </div>

Input properties


Target property declaration

@Component({
  inputs: ['article'],
})
<article-detail [article]="selectedArticle">

Input properties