Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data from asp.NET MVC to Angular2

Tags:

What is the best way to pass data from an ASP.NET MVC controller to an Angular 2.0 component? For example, we use the ASP.NET MVC Model and would like to send a JSON version of it to Angular to use it in Angular.

When the controller is serving the view, we can already push some data to Angular2 (the model). So additional AJAX call to fetch that data is not required.

However, I am struggling to "inject" it into the Angular component. How do you do this? Any good references for this? As you may have noticed, I'm quite new to Angular2.

My index.cshtml looks like this.

<div class="container">
<div>
    <h1>Welcome to the Angular 2 components!</h1>
</div>
<div class="row">
    <MyAngular2Component>
        <div class="alert alert-info" role="alert">
            <h3>Loading...</h3>
        </div>
    </MyAngular2Component>
</div>
</div>

Kind regards,

Rob

like image 389
Rob Van Pamel Avatar asked Apr 25 '16 12:04

Rob Van Pamel


1 Answers

The best way that I have found to pass data in from MVC (or any hosting/startup page) is to specify the data as an attribute on the bootstrapped component, and use ElementRef to retrieve the value directly.

Below is an example for MVC derived from the this answer, which states that it is not possible to use @Input for root-level components.

Example:

//index.cshtml
<my-app username="@ViewBag.UserName">
    <i class="fa fa-circle-o-notch fa-spin"></i>Loading...
</my-app>


//app.component.ts
import {Component, Input, ElementRef} from '@angular/core';

@Component({
    selector: 'my-app',
    template: '<div> username: <span>{{username}}</span> </div>'
})
export class AppComponent {
    constructor(private elementRef: ElementRef) {}

    username: string = this.elementRef.nativeElement.getAttribute('username')
}

If you want to retrieve more complex data that is not suitable for an attribute, you can use the same technique, just put the data in a HTML <input type='hidden'/> element or a hidden <code> element, and use plain JS to retrieve the value.

myJson: string = document.getElementById("myJson").value

Warning: Access the DOM directly from a data-bound application such as Angular, breaks the data-binding pattern, and should be used with caution.

like image 171
Joseph Gabriel Avatar answered Sep 23 '22 19:09

Joseph Gabriel