首页 > 解决方案 > 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

标签: angularangular6

解决方案


正如您已经指出的那样,您需要使用注入器,它将提供所有必要的依赖数据。

我的父组件

@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 编辑器上编写,因此可能存在拼写错误和语法错误。请纠正自己。


推荐阅读