Monday, November 21, 2016

Angular 2 Part 3.2 - Component HTML & CSS

Our application does not look nice without CSS decoration. I am going to add CSS into our component decorator by introduce styles.

@Component({
  selector: "car-parts", // Display in selector defined in app.component.ts
  template: `
    <p>There are {{totalCarParts()}} total parts in stock.</p>
    <ul>
      <!-- carParts in an array object defined in AppComponent Class. -->
      <!-- carPart is a local variable. -->
      <li *ngFor="let carPart of carParts">
        <h2>{{carPart.name | uppercase}}</h2>
        <p class="description">{{carPart.description}}</p>
        <p class="price">{{carPart.price | currency:"EUR":true}}</p>
        <p *ngIf="carPart.inStock > 0">{{carPart.inStock}} in stock</p>
        <p *ngIf="carPart.inStock === 0">Out of stock</p>
      </li>
    </ul>
  `,
  styles: [`
    .description { 
      color: #ff0000;
      font-size: small;
    }
    .price{
      font-weight: bold;
    }
  `]
})

Here is out put.





















Can we have same CSS Class Name in different component in same page? Answer is Yes, because Angular scope the CSS Class. Confusing? Try to create same Class Name in different component in same page and view browser's source, you should understand.

Huh... Now we have JavaScript, HTML and CSS in same file. Is it messy and hard to maintenance when scale? Let's split our HTML and CSS into different file by using component decorator templateUrl and styleUrls. HTML will store in car-parts.component.html and CSS will store in car-parts.component.css.

car-parts.component.html
<p>There are {{totalCarParts()}} total parts in stock.</p>
<ul>
  <!-- carParts in an array object defined in AppComponent Class. -->
  <!-- carPart is a local variable. -->
  <li *ngFor="let carPart of carParts">
    <h2>{{carPart.name | uppercase}}</h2>
    <p class="description">{{carPart.description}}</p>
    <p class="price">{{carPart.price | currency:"EUR":true}}</p>
    <p *ngIf="carPart.inStock > 0">{{carPart.inStock}} in stock</p>
    <p *ngIf="carPart.inStock === 0">Out of stock</p>
  </li>
</ul>
car-parts.component.css
.description {
  color: #ff0000;
  font-size: small;
}

.price{
  font-weight: bold;
}
car-parts.component.ts
@Component({
  selector: "car-parts", // Display in selector defined in app.component.ts
  templateUrl: "app/car-parts.component.html",
  styleUrls: ["app/car-parts.component.css"]
})
Again, no new functionality, just splitting the files.

Download Car Part Source:
https://github.com/htsiah/angular2-carparts

No comments:

Post a Comment