Angular 6-如何在ngComponentOutlet

时间:2018-11-29 14:30:25

标签: angular angular6

我是6号角的新手。

我在for循环中使用ngComponentOutlet

我想知道如何将数据传递给子组件

我的HTML

<div *ngFor="let item of items">
    <ng-container *ngComponentOutlet="currentComponent"></ng-container>
</div>

我的父组件,决定要选择哪个组件

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];
	}
}

我的孩子部分

export class FirstchildComponent implements OnInit {
	@Input() magazineData: any[];
	constructor() { }

	ngOnInit() {
	}
}

所以我想将项目(循环的单个项目)作为输入传递给FirstchildComponent

我该怎么办?

我已经检查了喷油器

但是我是新来的,我不太了解喷油器的工作原理

2 个答案:

答案 0 :(得分:2)

正如您已经指出的那样,您需要使用将提供所有基本依赖项数据的Injector。

MyParentComponent

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

答案 1 :(得分:0)

创建动态组件时,

ViewContainerRef,ComponentFactoryResolver使其比ngComponentOutlet更容易。

动态组件

模板-

<div #dynamicComponent></div>

TS - 
@ViewChild('dynamicComponent', { read: ViewContainerRef }) podViewContainerRef;
  constructor(private resolver: ComponentFactoryResolver) {
  }

  ngAfterViewInit() {
    let componentFactory;
    let componentRef;
    try {
      componentFactory = this.resolver.resolveComponentFactory(pod.component);
      componentRef = this.podViewContainerRef.createComponent(componentFactory);
      componentRef.instance.podInfo = this.podInfo;
    } catch (e) {
      console.log(e);
    }
  }
相关问题