首页 > 解决方案 > 无法绑定到“ngModel”,因为它不是“p-autoComplete”的已知属性

问题描述

我已经安装了 PrimeNg。我正在使用p-autoComplete组件,但现在发生此错误。我到处检查,但找不到任何东西。另外,我只是想复制一个官方的 PrimeNg 演示。p-自动完成组件。

1 - 我已经像这样安装了 PrimeNg。

npm install primeng --save
npm install primeicons --save

2 - 我已经像这样将模块添加到我的 app.component.ts 文件中。

import { AutoCompleteModule } from 'primeng/autocomplete';
//other imports
@NgModule({
declarations: [
  AppComponent,
  HomeComponent
],
imports: [
  BrowserModule,
  AutoCompleteModule
],
  providers: [CountryServiceService],
  bootstrap: [AppComponent]
})
export class AppModule { }

3 - 使用 Angular Cli 我创建了一个服务并添加了来自 primeNg 官方网站的演示代码。

4 - 我已经在我的 app.component.ts 文件中展示了我的服务,就像这样。

    import { CountryServiceService } from './country-service.service';
...
providers: [CountryServiceService],
...

5 - 创建了一个名为 home 的组件,在 home.component.html 中我复制并粘贴了官网 deme 代码。

<h3 class="first">Basic</h3>
<p-autoComplete [(ngModel)]="country"         
[suggestions]="filteredCountriesSingle"         (completeMethod)="filterCountrySingle($event)" field="name" [size]="30"     placeholder="Countries" [minLength]="1"></p-autoComplete>
<span style="margin-left:10px">Country: {{country ? country.name||country : 'none'}}</span>
<h3>Advanced</h3>
<p-autoComplete [(ngModel)]="brand" [suggestions]="filteredBrands" (completeMethod)="filterBrands($event)" [size]="30" [minLength]="1" placeholder="Hint: type 'v' or 'f'" [dropdown]="true">
  <ng-template let-brand pTemplate="item">
    <div class="ui-helper-clearfix" style="border-bottom:1px solid #D5D5D5">
      <img src="assets/showcase/images/demo/car/{{brand}}.png" style="width:32px;display:inline-block;margin:5px 0 2px 5px" />
      <div style="font-size:18px;float:right;margin:10px 10px 0 0">{{brand}}</div>
    </div>
  </ng-template>
</p-autoComplete>
<span style="margin-left:50px">Brand: {{brand||'none'}}</span>
<h3>Multiple</h3>
<span class="ui-fluid">
    <p-autoComplete [(ngModel)]="countries" [suggestions]="filteredCountriesMultiple" (completeMethod)="filterCountryMultiple($event)" styleClass="wid100"
    [minLength]="1" placeholder="Countries" field="name" [multiple]="true">
    </p-autoComplete>
</span>
<ul>
  <li *ngFor="let c of countries">{{c.name}}</li>
</ul>

6 - 在 home.component.ts 文件中我复制并粘贴了官网演示代码。

7 - 在 app.component.html 中,我添加了我的主组件以查看是否一切正常。

所以,我做了这些步骤,但我没有得到想要的行为,或者我什至看不到渲染的 html 页面。

当我检查页面时,出现以下错误在此处输入图像描述

那么,我做错了什么。说真的!...愚蠢的 PrimeNg

标签: angulartypescriptprimeng

解决方案


您需要导入FormsModule,因为ngModel它是其中的一部分:

import { FormsModule }   from '@angular/forms';
         ^^^^^^^^^^^

import { AutoCompleteModule } from 'primeng/autocomplete';
//other imports
@NgModule({
declarations: [
  AppComponent,
  HomeComponent
],
imports: [
  BrowserModule,
  FormsModule,
  ^^^^^^^^^^^^
  AutoCompleteModule
],
  providers: [CountryServiceService],
  bootstrap: [AppComponent]
})
export class AppModule { }

推荐阅读