0

How do I feed static data to my app component? I would like to use the data during component initialization, a bit like ngInit in Angular 1.x

This is what I've tried:

MyView.cshtml

<some-viewing-app [workflows]="@Json.Encode(ViewBag.Workflows)"></some-viewing-app>

or

<some-viewing-app workflows="@Json.Encode(ViewBag.Workflows)"></some-viewing-app>

SomeViewingAppComponent.ts

export interface IWorkflowMap {
  [id: number]: string;
}

@Component({
  selector: 'some-viewing-app',
  providers: [...],
  template: `...`,
})
export class AppComponent {
  @Input()
  workflows: IWorkflowMap;

  ngOnInit() {
    this.leadApiService.workflows = this.workflows; // == undefined! :(
  }
}

I've also tried reading the workflows from the constructor with the same result. I would prefer this solution over fetching static with AJAX.

Leonard
  • 3,012
  • 2
  • 31
  • 52

1 Answers1

2

I "solved" it by using the ElementRef and the dataset property.

View.cshtml

<app data-workflows="@Json.Encode(ViewBag.Workflows)"></app>

app.component.ts

@Component({...})
export class AppComponent {
    constructor(rootElement: ElementRef) {
        workflows = JSON.parse(rootElement.nativeElement.dataset['workflows']);
    }
}
Leonard
  • 3,012
  • 2
  • 31
  • 52