I have a list of news articles returned from an API and a "Sort By" drop down, and once an option is selected I want to be able to refresh the page and have it remember the user selection and keep the articles sorted accordingly. Currently the article order is preserved but the "Sort By" drop down is resetting to the default ("Relevance") - how do I get the drop down to remember the user's selection in the UI on refresh?
I'm not getting and errors in the console and I've tried wrapping the FormControl in a FormGroup, initializing the FormControl to the value in session storage by default, and subscribing to ValueChanges on the FormControl but those didn't seem to work.
home.component.html
<input type="text" id="topic" name="topic" [formControl]="articleTopic">
<button type="submit" class="button-primary" (click)="getArticlesByTopic()">Submit</button>
<div class="filter" *ngIf="articles">
<label for="sort">Sort By:</label>
<select id="sort" [formControl]="selectedFilter" (click)="setSelectedFilter()">
<option *ngFor="let filter of filters">{{filter}}</option>
</select>
</div>
<div *ngIf="articles" class="articles">
<ng-container *ngFor="let article of articles | filter: selectedFilter.value">
<app-card [article]=article"></app-card>
</ng-container>
</div>
home.component.ts
export class HomeComponent implements OnInit {
filters: string[] = ['Relevance', 'Title', 'Date'];
selectedFilter = new FormControl();
articleTopic = new FormControl();
articles: Article[];
constructor(
private newsService: NewsService
) { }
ngOnInit() {
this.articleTopic.setValue(sessionStorage.getItem('topic'));
this.articles = JSON.parse(sessionStorage.getItem('articles'));
this.selectedFilter.setValue(sessionStorage.getItem('filter'));
}
getArticlesByTopic() {
sessionStorage.setItem('topic', this.articleTopic.value);
this.newsService.getArticlesByTopic(this.articleTopic.value).subscribe(response => {
this.articles = response;
});
}
setSelectedFilter() {
sessionStorage.setItem('filter', this.selectedFilter.value);
}
}
What am I missing?
You need to set [value]
on the select, something like :
ts:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
selectedFilter;
ngOnInit() {
this.selectedFilter = "val2";
}
}
html:
<select [value]="selectedFilter">
<option value="val1">1</option>
<option value="val2">2</option>
<option value="val3">3</option>
<option value="val4">4</option>
</select>
Here is a basic repro on Stackblitz