Angular4: How to add an input value to the ngComponentOutlet directive?

I have a component like:

@Component({ selector: 'app-item', template: '<p>{{title}}</p>' }) export class TitleComponent { @Input() title:string; } @Component({ selector: 'app-foo', template: '<ng-container *ngComponentOutlet="outlet"></ng-container>' }) export class FooComponent { outlet = TitleComponent; } 

How to pass input header value in ng container for TitleComponent or how can I set this value?

+5
source share
2 answers

As mentioned by Reno , you can use an injector to enter values.

For completeness, here is an example with the dynamic value "title":

 export const TITLE = new InjectionToken<string>('app.title'); @Component({ selector: 'app-item', template: '<p>{{title}}</p>' }) export class TitleComponent { @Input() title:string; constructor(@Inject(TITLE) titleInjected: string){ this.title = this.title || titleInjected; } } @Component({ selector: 'app-foo', template: '<ng-container *ngComponentOutlet="outlet; injector: myInjector"></ng-container>' }) export class FooComponent { outlet = TitleComponent; myInjector: Injector; constructor(injector: Injector){ let title = 'My dynamic title works!'; this.myInjector = ReflectiveInjector.resolveAndCreate([{ provide: TITLE, useValue: title }], injector); } } @NgModule({ providers: [ { provide: TITLE, useValue: '' } ] }) export class AppModule { } 
+3
source

An example solution is shown in the ngComponentOutlet documentation , specifically a second example with @Injectable , like titusfx .

Here's what it looks like in your use case:

 @Injectable() class Info { title = 'a little hacky'; } @Component({ selector: 'app-item', template: '<p>{{info.title}}</p>' }) export class TitleComponent { // @Input() title:string; constructor(public info: Info){ } } @Component({ selector: 'app-foo', template: '<ng-container *ngComponentOutlet="outlet; injector: myInjector"></ng-container>' }) export class FooComponent { outlet = TitleComponent; myInjector: Injector; constructor(injector: Injector){ this.myInjector = ReflectiveInjector.resolveAndCreate([Info], injector); } } 
+1
source

Source: https://habr.com/ru/post/1263852/


All Articles