将下拉菜单的数字存储为整数AngularJS

yzuktlbb  于 2022-10-31  发布在  Angular
关注(0)|答案(1)|浏览(148)

我有一个下拉菜单,里面有数字。菜单是这样的:

<div class="container-fluid">
        <label>Choose number</label>
        <select ng-model="visitors_list" id="visitors">
            <option class="dropdown-item" value="1">1</option>
            <option class="dropdown-item" value="2">2</option>
            <option class="dropdown-item" value="3">3</option>
            <option class="dropdown-item" value="4">4</option>
            <option class="dropdown-item" value="5">5</option>
        </select>
    </div>

我的目标是根据我的选择将所需的数字存储为整数。例如,如果我选择2,则数字2将存储为变量中的整数。有什么方法可以实现这一点吗?

h22fl7wq

h22fl7wq1#

如果我没理解错的话,这应该就是你要找的东西,在html中添加一个事件到你的选择器中,如下所示($event将检索选定的值):

<select ng-model="visitors_list" id="visitors" (change)="onSelect($event)"> 
        <option class="dropdown-item" value="1">1</option>
        <option class="dropdown-item" value="2">2</option>
        <option class="dropdown-item" value="3">3</option>
        <option class="dropdown-item" value="4">4</option>
        <option class="dropdown-item" value="5">5</option>
</select>

在你的打字稿里:

export class YourComponent {

  selectedNumber!: number; // Create a variable called selectedNumber and set it to null.

  constructor() {}

  ngOnInit() {}

/**
 * The function takes an event as an argument, and sets the selectedNumber property to the value of the
 * event's target.
 * @param {any} event - any - The event object
 */
  onSelect(event: any) {
    this.selectedNumber = event.target.value;
  }

}

现在您可以随意使用变量了,希望我对您有所帮助

相关问题