2

I am trying to display rows of data on a page using Angular 2, TypeScript and ASP.NET MVC 4.5. I'm trying to deliver the JSON into an Angular 2 component, but I've not been able to succeed, and the browser isn't showing any errors.

Does anyone know how to return JSON data from a .NET controller, embed in a view using (@Html.Raw(Json.Encode(Model)), and then pass into an Angular 2 component/template to be displayed?

Here is what I have tried so far (built from various examples on Plunkr and examples from the AngularJS site. I'll note that I had a basic Angular 2 sample working in the same solution, so I believe the framework and tools are setup correctly. Just having difficulty applying it. I've been referencing this plunk on my latest attempt: http://plnkr.co/edit/LEtEN9?p=preview

In my view:

<my-app holdings="@Html.Raw(Json.Encode(Model))">Loading...</my-app>

main.ts:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './boot';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);

boot.ts:

///<reference path="./../typings/globals/core-js/index.d.ts"/>
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app';

@NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }

app.ts:

import { Component, Input } from '@angular/core';
@Component({
    selector: 'my-app',
    template: `    
    <ul>
      <li *ngFor="let report of holdings">
        {{ report.CorpName }}
      </li>
    </ul>
  `
})
export class AppComponent {
    @Input() holdings: any;
}

Thank you for your help!

jdooloukas
  • 21
  • 1
  • http://stackoverflow.com/questions/39614451/angular-2-input-binding-does-not-work/39614592#39614592 – yurzui Mar 28 '17 at 20:17

1 Answers1

0

Using the link provided by yurzui in the comments as well as the "hack" function by evanplaice here: https://github.com/angular/angular/issues/6392, I put together the following solution.

The changes are limited to the app.ts.

app.ts:

import { Component, Input, ElementRef } from '@angular/core';
@Component({
    selector: 'my-app',
    template: `   
    <ul>
      <li *ngFor="let report of hack(holdings)">
        {{ report.CorpName }}
      </li>
    </ul>
  `
})
export class AppComponent {

    hack(val) {
        console.log('Before:');
        console.log(val);
        val = JSON.parse(val);
        console.log('After:');
        console.log(val);
        return val;
    }

    @Input() holdings: any;

    constructor(elm: ElementRef) {
        this.holdings = elm.nativeElement.getAttribute('holdings');
    }
}
jdooloukas
  • 21
  • 1