如何正确使用PrimeNG的Dropdown

How to use PrimeNG's Dropdown correctly

我已经关注了 this and 问题,但他们的问题与我的略有不同。事实上,第一个问题甚至没有正确的答案。尽管正确地遵循了 primeng 文档中的所有内容,但我还是收到了这个错误:

这是我的代码。

app.module.ts

//... 
import {DropdownModule} from 'primeng/dropdown';

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    ...,
    DropdownModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

我还使用命令安装了 @angular/cdknpm install @angular/cdk --save

package.json

"dependencies": {
    ...
    "@angular/cdk": "^8.2.3",
    ...
    "primeicons": "^2.0.0",
    "primeng": "^8.1.1",
    ...
  },

而我的app.component.html是:

  <p-dropdown [options]="cities1" [(ngModel)]="selectedCity1"></p-dropdown>

我的app.component.ts是:

import { Component, OnInit } from '@angular/core';
import {SelectItem} from 'primeng/api';

interface City {
  name: string;
  code: string;
}

@Component({
  ...
})    
export class ContainerComponent implements OnInit {

  cities1: SelectItem[];
  selectedCity1: City;

  constructor() {
    this.cities1 = [
      {label:'Select City', value:null},
      {label:'New York', value:{id:1, name: 'New York', code: 'NY'}},
      {label:'Rome', value:{id:2, name: 'Rome', code: 'RM'}},
      ...
  ];
  }

  ngOnInit() {
  }
}

请指正。

PS: 我也找到了一个stackblitz。却学不到多少东西。

我创建了一个带有 primeNg 下拉菜单的最小 stackbitz,因此您可以单独查看它。

您需要根据 PrimeNg Get started 部分将 css 添加到 angular.json 文件并将一些依赖项添加到 package.json 文件。

那应该让你朝着正确的方向前进