在 AngularJs 中設定 Select From Typescript 的預設選項值

Muhammad Ibrahim Alvi 2024年2月15日
  1. 在 AngularJS 中通過 Value 屬性選擇預設值
  2. 通過 AngularJS 中的 ngModel 選擇器選擇預設值
在 AngularJs 中設定 Select From Typescript 的預設選項值

select 是一個 HTML 標記,其中包含 n 個包含 value 屬性的選項子標記。

如果使用者沒有選擇任何特定的定義值,本教程指南將提供如何從 AngularJs 中的 TypeScript 中選擇選擇預設選項值。

在 AngularJS 中通過 Value 屬性選擇預設值

我們可以通過在陣列括號內設定 value 屬性併為其分配一個硬塗層值來為 select 標籤定義一個預設值。

select 標籤的預設 value 只能從選項值中分配。這個值也可以使用在 change 事件中呼叫的 valueChanging 函式來處理。

傳遞給 valueChanging 函式的引數可以指定一個預設選項。

<select  class='form-handler'
        (change)="valueChanging($event)" [value]='69'>
  <option value='68'>68</option>
  <option value='69'>69</option>
  <option value='70'>70</option>
</select>

在 Visual Studio IDE 中 app.component.html

輸出:

Visual Studio IDE app.component.html 輸出

預設情況下,選擇預設的選擇選項。如果你記得只將值作為預設選項放在 select 選項值中,那將會有所幫助。

通過 AngularJS 中的 ngModel 選擇器選擇預設值

我們可以使用 ngModel 選擇器,AngularJs 中的一個指令,它繫結 inputselecttextarea,並將 user 值儲存在變數中。

select 標籤包含帶有 selectValue 屬性的 ngModel 指令,並且在 app.component.ts 檔案中,它被分配了一個與 option 標籤內相同的預設值。

app.component.html

<select [(ngModel)]='selectValue' class='form-control'>
  <option value='47'>47</option>
  <option value='46'>46</option>
  <option value='45'>45</option>
</select>

在 AngularJs 中使用 nrSelect

app.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  selectValue:number = 47;
}

在 AngularJs 中使用 nrSelect

輸出:

Visual Studio IDE app.component.html 輸出

Muhammad Ibrahim Alvi avatar Muhammad Ibrahim Alvi avatar

Ibrahim is a Full Stack developer working as a Software Engineer in a reputable international organization. He has work experience in technologies stack like MERN and Spring Boot. He is an enthusiastic JavaScript lover who loves to provide and share research-based solutions to problems. He loves problem-solving and loves to write solutions of those problems with implemented solutions.

LinkedIn