ngfor in ionic 5 code example
Example 1: ionic ngfor in component
I'm going crazy, i've created a new component and he's working fine. Now i would like to use this on two pages.
Then i've created a component module (/components/all-components.module.ts) like this :
import { NgModule } from '@angular/core';
import { TagsComponent } from './tags/tags.component';
import { IonicModule } from '@ionic/angular';
@NgModule({
imports: [IonicModule],
declarations: [
TagsComponent
],
exports: [
TagsComponent
]
})
export class AllComponentsModule {}
I've added on app.module.ts the AllComponentsModule and on my 2 pages module i have added same.
Now, my component work fine when i'm displaying text or variable, my console.log return the data, but if i use *ngFor nothing appear.
Finally, here's my component
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-tags',
templateUrl: './tags.component.html',
styleUrls: ['./tags.component.scss'],
})
export class TagsComponent implements OnInit {
@Input() userTags: any;
constructor() {
}
ngOnInit() {
console.log(this.userTags);
}
}
And the view:
<p>hi</p>
<div *ngFor="let tag of userTags">
<p>{{tag?.name}}</p>
</div>
Ok i don't understand why but if i use a module to store all of components. On my all-components.module.ts i have to put the CommonModule to interpret *ngFor, *ngIf, etc.
With CommonModule import all working fine !
Here's the code updated:
import { NgModule } from '@angular/core';
import { TagsComponent } from './tags/tags.component';
import { CommonModule } from "@angular/common";
@NgModule({
imports: [CommonModule],
declarations: [
TagsComponent
],
exports: [
TagsComponent
]
})
export class AllComponentsModule {}
Example 2: ngfor ionic example
<ion-select placeholder="Select" [(ngModel)]="selected">
<ion-option *ngFor="let item of strings" [value]="item">{{item}}</ion-option>
</ion-select>`