Bind query string params to model in Angular 2

 ̄綄美尐妖づ 提交于 2019-12-13 05:26:01

问题


I have an app similar to Google Maps. I would like to sync my model with query string params.

What do I mean by this?

Suppose you have a simple map object. You enter the site and you get default bounds set in the map component. But when you change something (pan/zoom/etc.), I want your changes to be set also in query string for location sharing things.

How to do this properly?


回答1:


I will show you the way I implemented it but I'm not sure if it's a proper way to do it though.

The idea is:

First, I add a hidden input to record the change of map object simultaneously:

<input hidden id='hiddenMapValue' #hiddenInput>

#hiddenInput is there for a purpose and you'll see it.

Then, every time map object changes, assign the value to this hidden input, for example:

$("#hiddenMapValue").val(place.geometry.location).trigger('change');

In your component:

@ViewChild('hiddenInput') hiddenInput: ElementRef;
ngAfterViewInit(){
 $(this.hiddenInput.nativeElement).on('change',  (e)=>{
  this.onInputChanged(e);
 });
}

private onInputChanged(e): void{
 //This is your changed location value
 console.log(e.target.value);
}

@ViewChild('hiddenInput') hiddenInput: ElementRef; is how you get a hold on hidden input #hiddenInput.

And no, angular 2 model does not record changes made by jQuery. This is an alternate solution to this problem, so far.

I hope this will help.




回答2:


Inject in your constructor:

activatedRoute: ActivatedRoute,
router: Router

To update the URL you can use:

this.router.navigate(
  [this.param],
  {
    queryParams: {
      queryParamKey: this.queryParam,
    }
  });

To subscribe to changes to the URL changing you can use:

this.activatedRoute.paramMap.subscribe((params: ParamMap) => {
  // remember to add /:paramKey to your routing!
  this.param = params.get('paramKey');
  this.update();
});

this.activatedRoute.queryParams.subscribe((params: { [key: string]: any }) => {
  this.queryParam = params['queryParamKey'];
});

This way you'll be able to make sure that everything is specified in the URL, since all your changes are pushed and pulled through it.



来源:https://stackoverflow.com/questions/38845490/bind-query-string-params-to-model-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!