Angular: How to pass data in ngComponentOutlet through Injector

前端 未结 3 803
清酒与你
清酒与你 2021-01-20 10:02

I\'m trying to dynamically create and show component and i need to pass some data into it, so that it knows what to show.

Here is my code:

html part:

3条回答
  •  盖世英雄少女心
    2021-01-20 10:48

    If you open code of NgComponentOutlet directive:

    @Directive({selector: '[ngComponentOutlet]'})
    export class NgComponentOutlet implements OnChanges, OnDestroy {
      @Input() ngComponentOutlet: Type;
      @Input() ngComponentOutletInjector: Injector;
    

    you can notice that it takes ngComponentOutlet input that should have type Type but you're passing object to it.

    Also we can see that this directive can take Injector as @Input. So lets leverage this knowledge to do your task.

    For example we wrote template like:

    
    

    Now lets declare component and injector properties in component class:

    @Component({...})
    export class AppComponent  {
    
      component: Type;
      injector: Injector;
    
      constructor(private inj: Injector) {}
    
      ngOnInit() {
        this.component = ProjectComponent; // note: we're passing type here
        this.injector = Injector.create([
          { provide: BasicProject, useValue: new Project('test name') }
        ], this.inj);
      }
    }
    

    and your ProjectComponent now uses angular DI mechanism to get data we passed to injector:

    export class ProjectComponent {
      name: string;
    
      constructor(project: BasicProject) {
        this.name = project.name;
      }
    }
    

    Stackblitz Example

提交回复
热议问题