Asked  7 Months ago    Answers:  5   Viewed   37 times

In one of my Angular 2 routes's templates (FirstComponent) I have a button

first.component.html

<div class="button" click="routeWithData()">Pass data and route</div>

My goal is to achieve:

Button click -> route to another component while preserving data and without using the other component as a directive.

This is what I tried...

1ST APPROACH

In the same view I am storing collecting same data based on user interaction.

first.component.ts

export class FirstComponent {
     constructor(private _router: Router) { }

     property1: number;
     property2: string;
     property3: TypeXY; // this a class, not a primitive type

    // here some class methods set the properties above

    // DOM events
    routeWithData(){
         // here route
    }
}

Normally I'd route to SecondComponent by

 this._router.navigate(['SecondComponent']);

eventually passing the data by

 this._router.navigate(['SecondComponent', {p1: this.property1, p2: property2 }]);

whereas the definition of the link with parameters would be

@RouteConfig([
      // ...
      { path: '/SecondComponent/:p1:p2', name: 'SecondComponent', component: SecondComponent} 
)]

The issue with this approach is that I guess I can't pass complex data (e.g. an object like property3) in-url;

2ND APPROACH

An alternative would be including SecondComponent as directive in FirstComponent.

  <SecondComponent [p3]="property3"></SecondComponent>

However I want to route to that component, not include it!

3RD APPROACH

The most viable solution I see here would be to use a Service (e.g. FirstComponentService) to

  • store the data (_firstComponentService.storeData()) on routeWithData() in FirstComponent
  • retrieve the data (_firstComponentService.retrieveData()) in ngOnInit() in SecondComponent

While this approach seems perfectly viable, I wonder whether this is the easiest / most elegant way to achieve the goal.

In general I'd like to know whether I'm missing other potential approaches to pass the data between components, particularly with the less possible amount of code

 Answers

35

update 4.0.0

See Angular docs for more details https://angular.io/guide/router#fetch-data-before-navigating

original

Using a service is the way to go. In route params you should only pass data that you want to be reflected in the browser URL bar.

See also https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

The router shipped with RC.4 re-introduces data

constructor(private route: ActivatedRoute) {}
const routes: RouterConfig = [
  {path: '', redirectTo: '/heroes', pathMatch : 'full'},
  {path : 'heroes', component : HeroDetailComponent, data : {some_data : 'some value'}}
];
class HeroDetailComponent {
  ngOnInit() {
    this.sub = this.route
      .data
      .subscribe(v => console.log(v));
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}

See also the Plunker at https://github.com/angular/angular/issues/9757#issuecomment-229847781

Tuesday, June 1, 2021
 
vuliad
answered 7 Months ago
89

There is a very simple approach and a very complex one.

The simple approach is to use raw HTML with anchor element outside of angular without RouterLink. Register to clicks on that anchor element and use the Router service to navigate.

The task was to fire links but the actual problem is far deeper, now it links next time its showing an angular component...

So, for the complex solution:

This is an highly advanced topic... Not only it involves using advanced angular techniques it's also advanced in the leaflet implementation.

I'll do my best to convey the message but due to the complexity the examples will be very simple and will require work.

First - Angular realm.

An HTML string that contains directives, components or pipes will never work, the only way is to initialize a View

Let's define A View as a reference to view instance of a component or a template.

These are called ComponentRef and TemplateRef

So, we have 2 ways to solve this problem. Since I can't do both i'll go with ComponentRef but note that you can also use TemplateRef. With templates you'll first need to obtain a template defined in the component as well as a ViewContainerRef to attach that template to.

We will build a service that accepts a leaflet Marker and binds to the click event of the marker, on click it will open a popup which is an angular Component.

The component is simple, it renders a link.

@Component({
  selector: 'facility-link',
  template: `Facility <br/> <a routerLink="{{link}}"> View Two</a>`
})
export class FacilityLinkComponent {
  public link: string;
  constructor() { }
}

Now, for the service:

@Injectable()
export class LinkPopupService {

  constructor(private cfr: ComponentFactoryResolver,
              private injector: Injector,
              private appRef: ApplicationRef) { }


  register(marker: leaflet.Marker, link: string): void  {
    marker.on('click', ($event: leaflet.MouseEvent)  => this.popup($event.target, link) );
  }

  popup(marker: leaflet.Marker, link: string) {
    const cmpFactory = this.cfr.resolveComponentFactory(FacilityLinkComponent);
    const componentRef = cmpFactory.create(this.injector);
    componentRef.instance.link = link;
    this.appRef.attachView(componentRef.hostView);
    const markerElement = marker.getElement();
    markerElement.parentElement.appendChild(componentRef.location.nativeElement);

    const markerPos = leaflet.DomUtil.getPosition(markerElement);
    const markerClass = leaflet.DomUtil.getClass(markerElement);


    leaflet.DomUtil.setTransform(componentRef.location.nativeElement, markerPos);
    leaflet.DomUtil.setClass(componentRef.location.nativeElement, markerClass);
  }
}

The register method accepts a marker and the link and registers to the click event.

When the popup method fires it uses angular tools to create a view instance of FacilityLinkComponent, set the link for future binding, attach a view to it and attach it to the DOM.

This all happens in the first 5 lines of code.

Some notes:

  • We must attach a view so change detection works
  • A Proper implementation will allow to set ViewContainerRef and / or an Injector - this is a must when using lazy loading.
  • It is preferred sending data to the component via Injector and not by assignment (ReflectiveInjector)
  • Proper clean up is required (destroy the component and detach the view)
  • Need to add toggle logic, also clean on navigation.

Leaflet

The code from the 6th line performs positioning of the popup.

This is a very simple logic, it just copies everything from the marker.

This is why I used a marker, so I'll have a reference to take the positioning from.

In a realworld example you'll need to get a panel and push the components into their own layer, computing the position. This is not that difficult since leaflet has all the helper, but it was too much for this.

Hope it helps.

Wednesday, July 28, 2021
 
hakimoun
answered 5 Months ago
10

Try the following:

<!DOCTYPE html>
<html >
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
</head>
<body ng-app="app">
    <div ng-controller="gridController">
        <!-- Initialise the grid with ng-init call -->
        <div ui-grid="gridOptions" ng-init="GetGridData(urlList)">
        </div>
    </div>

    <script src="Scripts/ng/angular.min.js"></script>
    <script src="Scripts/ng-grid/ui-grid.min.js"></script>
    <link rel="Stylesheet" type="text/css" href="Scripts/ng-grid/ui-rid.min.css" />

    <script type="text/javascript">

        var app = angular.module('app', ['ui.grid']);

        app.controller("gridController",
            ["$scope", "$attrs", "$element", "$compile", "$http", "$q",
            function ($scope, $attrs, $element, $compile, $http, $q)
            {
                $scope.urlList = "YourSourceUrl";

                function fnGetList(url)
                {
                    var deferred = $q.defer();
                    $http.get(url)
                        .success(function (data)
                        {
                            deferred.resolve(data);
                        })
                        .error(function (errorMessage)
                        {
                            alert(errorMessage);
                            deferred.reject;
                        });
                    return deferred.promise;
                };

                $scope.GetGridData = function (url)
                {
                    console.log("In GetGridData: " + "Getting the data");

                    //  Test Only - un-comment if you need to test the grid statically.

                    //$scope.loadData = ([
                    //        {
                    //            "UserName": "Joe.Doe",
                    //            "Email": "Joe.Doe@myWeb.com"
                    //        },
                    //        {
                    //            "UserName": "Jane.Doe",
                    //            "Email": "Jane.Doe@myWeb.com"
                    //        },
                    //]);
                    //return;

                    fnGetList(url).then(function (content)
                    {
                        //  Assuming your content.data contains a well-formed JSON

                        if (content.data !== undefined)
                        {
                            $scope.loadData = JSON.parse(content.data);
                        }
                    });
                };

                $scope.gridOptions =
                {
                    data: 'loadData',
                    columnDef:
                        [
                            { field: 'UserName', name: 'User' },
                            { field: 'Email', name: 'e-mail' }
                        ]
                };

            }
        ]);
</script>

</body>

If you do not want to populate the grid immediately, delete the call to

ng-init

and call the associated function on some other event.

Hopefully, without knowing much more about your specific problem, this will guide you to the solution.

Cheers.

Wednesday, August 18, 2021
 
fillobotto
answered 4 Months ago
91

To push 8-byte values such as doubles, you won't be able to use a regular PUSH instruction. And neither do you push floating-point parameters (or doubles) on to the floating-point stack. You need to put these fat parameters on the stack 'by hand'. For example, to push π as a parameter to a function f:

  __asm {
    FLDPI                    // load pi onto FP stack
    SUB ESP,8                // make room for double on processor stack
    FSTP QWORD PTR [ESP]     // store pi in proc stack slot (and pop from FP stack)
    CALL f
    ADD ESP,8                // clean up stack (assuming f is _cdecl)
  }
Monday, October 11, 2021
 
Maya
answered 2 Months ago
16

Try to import MdRippleModule in your AppModule:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';
import { HttpModule} from '@angular/http';
import { MdRippleModule } from '@angular2-material/core/core'; <== this line

@NgModule({
  imports:      [ BrowserModule, HttpModule, MdRippleModule ], <== add here
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Or pass MdRipple directive within your component:

...
import { MdRipple } from '@angular2-material/core/core'; <== this line
@Component({
  moduleId: module.id,
  selector: 'nav-bar',
  templateUrl: 'nav-bar.component.html',
  styleUrls: ['nav-bar.component.css'],
  directives: [ 
    MdToolbar, 
    MdButton,
    MdIcon,
    MdRipple <== add here
  ],
  providers: [ 
    MdIconRegistry 
  ]
})
export class NavBarComponent implements OnInit {
...
Tuesday, November 9, 2021
 
napolux
answered 1 Month ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share