在Angular中,你可以使用Angular Material库中的MatSelect组件来实现在下拉按钮上显示下拉项的功能。以下是一个示例代码:
ng add @angular/material
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-dropdown',
templateUrl: './dropdown.component.html',
styleUrls: ['./dropdown.component.css']
})
export class DropdownComponent {
dropdownList = ['Option 1', 'Option 2', 'Option 3'];
selectedOption = new FormControl('');
constructor() { }
}
Select an option
{{ option }}
在这个示例中,dropdownList
是一个包含下拉项的数组,selectedOption
是一个FormControl对象,用于追踪选择的下拉项的值。*ngFor
指令用于在MatOption组件中循环渲染下拉项。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatSelectModule } from '@angular/material/select';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule, ReactiveFormsModule, MatSelectModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
通过这些步骤,你就可以在Angular中实现在下拉按钮上显示下拉项的功能了。