angular - Angular 6 - How to pass data in ngComponentOutlet
问题描述
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
解决方案
正如您已经指出的那样,您需要使用注入器,它将提供所有必要的依赖数据。
我的父组件
@Component({...})
export class MyParentComponent {
constructor(private inj: Injector) {}
createInjector(item){
let injector = Injector.create([
{ provide: Item, useValue: item }
], this.inj);
return injector;
}
}
物品等级
如果没有,您将拥有该课程,Item
然后创建具有所有属性的新课程-
@Injectable()
export class Item{
...
}
html
<div *ngFor="let item of items">
<ng-container *ngComponentOutlet="currentComponent; injector:createInjector(item)"></ng-container>
</div>
动态组件
export class FirstchildComponent implements OnInit {
@Input() magazineData: any[];
constructor() { }
ngOnInit(private item : Item) { //<-- item content is here.
}
}
注意:代码已直接在 stackoverflow 编辑器上编写,因此可能存在拼写错误和语法错误。请纠正自己。
推荐阅读
- clojure - 从本地使用 boot-clj 依赖项
- reactjs - 如何在单击按钮时在不同的窗口中打开 jsx 组件?
- css - 如何在ionic4的类中调用变量?
- c# - 获取 dll 的路径 - 原始路径,而不是阴影程序集
- java - java cmd进程中如何按顺序执行多个命令
- java - 带有流弹簧引导的 DTO 映射
- java - 如何让处理在文本文件中获取数组的一项并对其做出决定
- image - 取消选择时停止 Gimp 合并图层
- angular-calendar - 角日历 | 需要一个默认的滚动视图到 8AM-11PM 在日/周中具有固定的标题
- django - 如何通过按下按钮更新 Django 中的页面