【问题标题】:How to get selected value of dropdown in angular 6 on load(not onchange)如何在加载时获取角度 6 中下拉列表的选定值(不是 onchange)
【发布时间】:2019-05-23 17:47:05
【问题描述】:

我有一个选择下拉菜单,我通过循环从数组中获取选项的数据和值。在这里,我需要在没有 onchange 的情况下加载页面时获取选定下拉列表的值(在本例中为最近)。下面是代码。

app.component.html

<select>
  <option *ngFor="let v of values" [value]="v.id">  
    {{v.name}}
  </option>
</select>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  title = 'projectchart';
 public values = [
  { id: 3432, name: "Recent" },
  { id: 3442, name: "Most Popular" },
  { id: 3352, name: "Rating" }
];
  ngOnInit(){
  alert('The default selected value is');
  }


}

【问题讨论】:

  • 你能用FormsModule吗?

标签: html angular typescript


【解决方案1】:

你可以使用响应式表单

constructor(private fb: FormBuilder) { }

// create a form group using the form builder service
formName = this.fb.group({
    name: ['']
})

在模板中

<form [formGroup]="formName">
 <select formControlName="name">
  <option *ngFor="let v of values" [value]="v.id">  
    {{v.name}}
  </option>
 </select>
</>

然后获取ts中的值:

this.formName.controls['name'].value

【讨论】:

  • 有没有不用formbuilder的简单方法
猜你喜欢
  • 2019-10-19
  • 2019-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-14
  • 1970-01-01
  • 2019-01-27
相关资源
最近更新 更多