【问题标题】:Getting the value of a dropdown before and after selection in Angular在Angular中选择之前和之后获取下拉列表的值
【发布时间】:2019-06-19 05:54:41
【问题描述】:

我目前正在为一个使用 Angular 的项目工作。我有一个下拉字段,我必须借助它来更新后端的状态。有没有办法获取下拉字段的旧值和当前值。

我已经尝试过使用“OnChanges”界面,但我无法实现任何目标。建议一些方法来获取选择前后的值。

【问题讨论】:

  • 显示尝试过的代码
  • @NSSK 在提问时始终提供您迄今为止尝试过的内容,这有助于回答问题
  • @NikhilGangurde 因为我是新手,所以我不知道确切的过程。我会听从您的建议,并会从下一次开始发布代码。谢谢
  • @PrashantPimpale 我会听从你的建议,并会从下一次开始发布代码。谢谢

标签: angular angular6


【解决方案1】:

您可以创建一个FormControl 并将其绑定到模板。

FormControl 实例上有一个 valueChanges Observable,您可以订阅它,以获取该控件当前选定的值。

但是如果你还想要之前的值,那么你可以使用pairwiseRxjs 运算符。像这样的:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { pairwise } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit, OnDestroy {
  name = 'Angular';
  selectListValue: FormControl = new FormControl();
  options = [
    'Option 1',
    'Option 2',
    'Option 3',
    'Option 4',
  ];
  subscription: Subscription;

  ngOnInit() {
    this.subscription = this.selectListValue.valueChanges
      .pipe(pairwise())
      .subscribe(changes => console.log(changes));
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

在你的模板中:

<select [formControl]="selectListValue" name="" id="">
  <option value="">Please select an Option</option>
  <option *ngFor="let option of options" [value]="option">{{option}}</option>
</select>

PS:因为FormControl 的默认值是undefined,所以它不会在第一次选择时给你一个值。如果您第一次也想要上一个和下一个值,请为 FormControl 分配一个默认值。

【讨论】:

  • 感谢您的帮助。你用详细的解释帮我解决了我的问题。谢谢
猜你喜欢
  • 2011-05-03
  • 2019-05-02
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多