将输入值传递给ngComponentOutlet创建的组件? [英] Pass an input value into a ngComponentOutlet created component?

查看:415
本文介绍了将输入值传递给ngComponentOutlet创建的组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的组件:

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

如何在ng容器上为TitleComponent传递输入标题值,或者如何设置该值?

How do you pass input title value on the ng-container for the TitleComponent or how can I set this value?

推荐答案

正如 Reno 所述,您可以使用注入器注入值.

As Reno has already mentioned, you can use an injector to inject values.

为了完整起见,下面是一个带有动态"title"值的示例:

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

export const TITLE = new InjectionToken<string>('app.title'); 


@Component({
  selector: 'app-item',
  template: '<p>{{title}}</p>'
})
export class TitleComponent implements OnInit {
  @Input() title:string;

  constructor(@Inject(TITLE) private titleInjected: string){

  } 

  ngOnInit() {
    this.title = this.title || this.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 { }

这篇关于将输入值传递给ngComponentOutlet创建的组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆