Skip to content
This repository was archived by the owner on Dec 4, 2017. It is now read-only.

Commit 6a35134

Browse files
committed
### Put Logic in the Component Class
1 parent 1c4d100 commit 6a35134

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

public/docs/ts/latest/guide/style-guide.jade

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -739,6 +739,59 @@ a(id='toc')
739739
<toh-hero (savedTheDay)="onSavedTheDay($event)"></toh-hero>
740740
```
741741

742+
<a href="#toc">Back to top</a>
743+
:marked
744+
### Put Logic in the Component Class
745+
<a id="04-16"></a>
746+
#### Style 04-16
747+
748+
- Put Component logic in the Component class, and not in the template.
749+
750+
*​*Why?**​: Logic will be contained in one place (the Component class) instead of being spread in two places.
751+
752+
*​*Why?**​: Keeping the logic of the components in their controller, instead of template will improve testability, maintability, reusability.
753+
754+
```typescript
755+
/* avoid */
756+
@Component({
757+
selector: 'toh-heroes-list',
758+
template: `
759+
<section>
760+
Your list of heroes:
761+
<hero-profile *ngFor="#hero of heroes" [hero]="hero">
762+
</hero-profile>
763+
Total powers: {{totalPowers}}<br>
764+
Average power: {{totalPowers / heroes.length}}
765+
</section>
766+
`
767+
})
768+
export class HeroesListComponent {
769+
heroes: Hero[];
770+
totalPowers: number;
771+
}
772+
```
773+
774+
```typescript
775+
/* recommended */
776+
@Component({
777+
selector: 'toh-heroes-list',
778+
template: `
779+
<section>
780+
Your list of heroes:
781+
<hero-profile *ngFor="#hero of heroes" [hero]="hero">
782+
</hero-profile>
783+
Total powers: {{totalPowers}}<br>
784+
Average power: {{avgPower}}
785+
</section>
786+
`
787+
})
788+
export class HeroesListComponent {
789+
heroes: Hero[];
790+
totalPowers: number;
791+
avgPower: number;
792+
}
793+
```
794+
742795
<a href="#toc">Back to top</a>
743796
:marked
744797
## Directives

0 commit comments

Comments
 (0)