Angular 表单控件下拉菜单不记得页面刷新时的选择

Angular formcontrol dropdown not remembering selection on page refresh

我有一个从 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>

这里是a basic repro on Stackblitz

如果 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>