0

How can I set initial state of Angular 2 app from view?

I have a controller that must pass initial state throw the view to angular 2 component.

  • What do u mean by it? Can you show me through code? – micronyks Mar 22 '16 at 02:45
  • You may want to have a look at this other [SO thread](http://stackoverflow.com/questions/36840967/how-to-pass-data-from-asp-net-mvc-to-angular2). I was going to flag yours as a duplicate of the other one, but then the other one has no confirmed answer yet, so... – superjos May 07 '16 at 09:59

2 Answers2

0

Currently you can't pass data to the root level component via a property, but you can however define a global variable outside the component and refer to it in your component. This might not be ideal, but perhaps not too bad either.

jquery is an example of this. In the below example the global jquery variable is referenced from my component. You could do the same with your own global variable. You could use server side rendering to dynamically create your global variable when the page renders.

import {Component, ElementRef, Inject, OnInit} from 'angular2/core';

    declare var jQuery:any;

    @Component({
        selector: 'jquery-integration',
        templateUrl: './components/jquery-integration/jquery-integration.html'
    })

    export class JqueryIntegration implements OnInit {
        elementRef: ElementRef;

        constructor(@Inject(ElementRef) elementRef: ElementRef) {
            this.elementRef = elementRef;
        }

        ngOnInit() {
            jQuery(this.elementRef.nativeElement).find('.moving-box').draggable({containment:'#draggable-parent'});
        }
    }
TGH
  • 38,769
  • 12
  • 102
  • 135
0

Why don't you hydrate the initial state of the application by calling a WebApi endpoint in ngOnInit()? That way your application is relying on a standard HTTP response rather than a piece of MVC infrastructure...

KnowHoper
  • 4,352
  • 3
  • 39
  • 54
  • Thank you for answer. The main problem is how to pass states between different views. – Zagir Aknazarov Mar 22 '16 at 04:23
  • Where are you bootstrapping your A2 app? In the view or in the _layout? – KnowHoper Mar 22 '16 at 05:59
  • A2 app bootstraps from View. But I'm interested in different ways of solution of this problem :) – Zagir Aknazarov Mar 22 '16 at 06:17
  • The issue you're having here is because you have essentially two conflicting MVW infrastructures. Setting variables on components is not good practice as its essentially a hack. I would recommend bootstraping angular2 in the index view, then use its router and SPA facilities to handle transitioning between views, client side, all data from the server can be fetched using its HTTP infrastructure. You will get a more responsive app this way and can preserve state using a service provided at app component level. Obviously your application may be complex and what i've suggested inappropriate. – KnowHoper Mar 22 '16 at 09:13