簡體   English   中英

如何在加載時獲得角度6下拉列表的選定值(不更改)

[英]How to get selected value of dropdown in angular 6 on load(not onchange)

我有一個選擇下拉列表,我通過循環從數組中獲取選項的數據和值。 這里我需要在沒有onchange的情況下加載頁面加載時選擇下拉值(在本例中為Recent)。 這是下面的代碼。

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


}

你可以利用反應形式

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM