Exception: Can"t bind to "ngFor" since it isn"t a known native property
π Angular Exception: Can't bind to 'ngFor' since it isn't a known native property π«
Are you getting this error message when working with Angular and trying to use the *ngFor
directive? Don't worry, you're not alone! This is a common issue faced by Angular developers, especially when working with the *ngFor
directive in Angular templates. But fear not, because in this blog post, we will walk you through the problem and provide you with easy solutions to fix it. So let's dive in! πͺ
The Problem πΎ
The error message Can't bind to 'ngFor' since it isn't a known native property
occurs when the Angular compiler cannot recognize the *ngFor
directive. This issue arises because the *ngFor
directive is part of the CommonModule
from @angular/common
, and it needs to be imported into your module file to make it work.
The Solution π‘
To fix this issue, follow these steps:
Step 1: Import the CommonModule
In your module file (usually named app.module.ts
), import the CommonModule
from @angular/common
at the top of the file:
import { CommonModule } from '@angular/common';
Step 2: Add the CommonModule
to the imports
array
Within the @NgModule
decorator, add CommonModule
to the imports
array:
@NgModule({
imports: [
CommonModule,
// other imports...
],
// other configurations...
})
Step 3: Check your template
Make sure you are using the *ngFor
directive correctly in your template. In the provided context, the syntax seems fine.
A Complete Example π
Here's an updated version of the code from the original question with the necessary changes:
import { bootstrap, Component, NgModule } from 'angular2/angular2';
import { CommonModule } from '@angular/common';
@Component({
selector: 'conf-talks',
template: `
<div *ngFor="let talk of talks">
{{ talk.title }} by {{ talk.speaker }}
<p>{{ talk.description }}</p>
</div>
`
})
class ConfTalks {
talks = [
{ title: 't1', speaker: 'Brian', description: 'talk 1' },
{ title: 't2', speaker: 'Julie', description: 'talk 2' }
];
}
@Component({
selector: 'my-app',
directives: [ConfTalks],
template: '<conf-talks></conf-talks>'
})
class App {}
@NgModule({
imports: [CommonModule],
declarations: [App, ConfTalks],
bootstrap: [App]
})
export class AppModule {}
bootstrap(AppModule);
Wrapping Up π
Now you know how to fix the error Can't bind to 'ngFor' since it isn't a known native property
. By importing the CommonModule
and adding it to the imports
array in your module file, you'll be able to use the *ngFor
directive without any issues. Remember to check your template for any possible mistakes in the usage of *ngFor
.
If you have any questions or still facing issues, let us know in the comments section below. We'd love to help you out! π¬
Keep coding, keep exploring! Happy Angular development! ππ
β¨Don't forget to follow our blog for more helpful tech tips and tricks!β¨