This Angular component displays a list of polls that are fetched from the server and has a slide toggle giving the authenticated user the option to display all polls or just the ones that the user has authored. I use Angular Material and Angular Flex Layout.
I'm specifically looking for feedback regarding best practices and how I handled displaying polls conditionally, but welcome all feedback. I chose to keep most of the conditional logic in the component instead of in the template but I'm not sure that is in accordance with Angular best practices.
poll-list.component.html
<div fxLayout="column" fxLayoutAlign="center" style="margin-top: 50px;">
<md-slide-toggle *ngIf="isLoggedIn()" (change)="displayMyPolls()" fxFlexAlign="center">Show only my polls</md-slide-toggle>
<md-nav-list fxFlexAlign="center">
<a md-list-item *ngFor="let poll of pollsToDisplay" [routerLink]="['/poll', poll.pollId]" class="bottom-border">
<md-icon md-list-icon>poll</md-icon>
<h1 md-line>{{poll?.question}}</h1>
<p md-line>{{poll?.getTotalVotes()}} votes</p>
</a>
</md-nav-list>
</div>
poll-list.component.ts
import { Component, OnInit } from '@angular/core';
import { PollService } from './poll.service';
import { AuthService } from '../auth/auth.service';
import { Poll } from './poll.model';
@Component({
selector: 'app-poll-list',
templateUrl: './poll-list.component.html',
styleUrls: ['./poll-list.component.css']
})
export class PollListComponent implements OnInit {
polls: Poll[] = [];
pollsToDisplay: Poll[] = [];
showOnlyMyPolls = false;
constructor(private pollService: PollService, private authService: AuthService) { }
ngOnInit() {
this.pollService.getPolls()
.subscribe(
(polls: Poll[]) => {
this.polls = polls;
this.pollsToDisplay = polls;
}
);
}
displayMyPolls() {
this.showOnlyMyPolls = !this.showOnlyMyPolls;
if (this.showOnlyMyPolls) {
this.pollsToDisplay = this.polls.filter((poll) => {
return this.authService.isLoggedInUser(poll.userId);
});
} else {
this.pollsToDisplay = this.polls;
}
}
isLoggedIn() {
return this.authService.isLoggedIn();
}
}