将输入值传递给ngComponentOutlet创建的组件?

Fra*_*n b 17 angular

我有一个组件,如:

@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;
}
Run Code Online (Sandbox Code Playgroud)

如何在titleComponent的ng-container上传递输入标题值,或者如何设置此值?

Pie*_*che 12

正如Reno已经提到的,您可以使用注射器来注入值.

为了完整起见,这是一个动态"标题"值的示例:

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 { }
Run Code Online (Sandbox Code Playgroud)

  • 您能否更新您的答案,它将适用于从父组件动态更改“标题”?我这样做了 - https://stackblitz.com/edit/angular-ngcomponentoutlet-input?file=src/app/app.component.ts 但也许有更好的解决方案 (2认同)
  • 很好的答案,尽管现在已弃用。检查这里的**复杂示例**以获取更多信息:https://angular.io/api/common/NgComponentOutlet (2认同)

Ren*_*aud 5

示例解决方案显示在ngComponentOutlet文档中,特别是第二个示例@Injectable,其中也提到了titusfx.

以下是您的用例的样子:

@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);
  }
}
Run Code Online (Sandbox Code Playgroud)