确认安装了 angular-select-country 库:使用命令 npm install angular-select-country --save
在 app.module.ts 文件中导入 AngularSelectCountryModule 并将其添加到 @NgModule 的 imports 数组中:
import { NgModule } from '@angular/core';
import { AngularSelectCountryModule } from 'angular-select-country';
@NgModule({
declarations: [
// ...
],
imports: [
// ...
AngularSelectCountryModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
其中,[(ngModel)]
是一个双向数据绑定的指令,selectedCountry
是选中的国家的值。
import { Component } from '@angular/core';
import { AscOptions } from 'angular-select-country';
@Component({
selector: 'app-country-selector',
template: `
`
})
export class CountrySelectorComponent {
selectedCountry = '';
ascOptions: AscOptions = {
includeCountries: ['CA', 'US', 'MX'], // 可选国家列表,如不设置则默认为所有国家。
excludeCountries: [] // 排除国家列表,如果某个国家存在于 excludeCountries 列表中,则不会显示在可选国家列表中。
};
}
这样就可以在组件中获取选择的国家了。