角度表单控件下拉列表不记得页面刷新时的选择



我有一个从API返回的新闻文章列表;排序依据";下拉菜单,一旦选择了一个选项,我希望能够刷新页面,让它记住用户的选择,并保持文章的相应排序。目前保留了物品顺序;排序依据";下拉菜单正在重置为默认值("相关性"(-如何让下拉菜单在刷新时记住用户在UI中的选择?

控制台中没有出现错误,我尝试过将FormControl封装在FormGroup中,将FormControl初始化为会话存储中的默认值,并在FormControl上订阅ValueChanges,但这些似乎都不起作用。

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);
}
}

我错过了什么?

您需要在select上设置[value],类似于:

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>

以下是Stacklitz 的基本演示

如果selectedFilter等于应选择项目的筛选值,则需要将value添加到选项中,并将selected与条件一起使用。

<div class="filter" *ngIf="articles">
<label for="sort">Sort By:</label>
<select id="sort" [formControl]="selectedFilter" (click)="setSelectedFilter()">
<option 
*ngFor="let filter of filters" 
[value]="filter" 
[selected]="selectedFilter.value === filter">
{{filter}}
</option>
</select>
</div>

最新更新