I am new in angular 6.
I am using ngComponentOutlet in a for loop
I want to know how can I pass the data to my child component
My HTML
<div *ngFor="let item of items">
<ng-container *ngComponentOutlet="currentComponent"></ng-container>
</div>
My parent component who decides which component to chose
export class MyParentComponent implements OnInit {
constructor(private route: ActivatedRoute, private commonService: CommonService) { }
dynamicComponents = {
'firstchild': {
'1': FirstchildComponent
}
};
currentComponent: any;
items: any;
ngOnInit() {
// To get data from resolver
const routeResult = this.route.snapshot.data.data.result;
this.items = routeResult.items;
// select child component at basis of route
const routeParams = this.route.snapshot.params;
this.currentComponent = this.dynamicComponents[routeParams.pageName][routeParams.templateType];
}
}
My child component
export class FirstchildComponent implements OnInit {
@Input() magazineData: any[];
constructor() { }
ngOnInit() {
}
}
So I want to pass item (single item of loop) to FirstchildComponent as a input
How can I do it?
I have checked with Injector
But as I am new, I don't really understand how injector works
As you already pointed out, you need to use the Injector, which will provide all essential dependency data.
###MyParentComponent
@Component({...})
export class MyParentComponent {
constructor(private inj: Injector) {}
createInjector(item){
let injector = Injector.create([
{ provide: Item, useValue: item }
], this.inj);
return injector;
}
}
###Item Class
You will be having the class for Item if not then create new one with all properties -
@Injectable()
export class Item{
...
}
<div *ngFor="let item of items">
<ng-container *ngComponentOutlet="currentComponent; injector:createInjector(item)"></ng-container>
</div>
###Dynamic Component
export class FirstchildComponent implements OnInit {
@Input() magazineData: any[];
constructor() { }
ngOnInit(private item : Item) { //<-- item content is here.
}
}
Note : The code has been written directly on stackoverflow editor so there could be typo and syntactical error. Please correct yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With