Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a new Angular tab with object data?

I am using Angular 7 and I would like to open a new Angular tab with object data. When the user clicks on the button, the object data will be sent and open a new tab with the data.

I have tried 3 things for that.

  1. I used 'window.open()'. I could open a new tab easily but I couldn't send big data like an object data.

let win = window.open('test-child', '_blank');

win.document.getElementById('text1');

  1. I also used Router. However it couldn't open a new tab. Just navigate to the url.

this.router.navigate(['test', obj]);

  1. I used the data service. I made data service and there are setValue and getValue. However, the child component couldn't get the data.

ex) data.service.ts

private _data = {};

setValue(value) { this._data = value; }

getValue() { return this._data;}

test.ts

obj = { name: 'pat', age: 30 };

openNewTab() { 
    this.data.setOption(this.obj); 
    windows.open('test-child', '_blank');
}

test-child.ts

data: any;

constructor(private dataService: DataService) {}

ngOnInit() { this.data = this.dataService.getValue(); }

So in this case, how can I send object data to open a new component tab in Angular? Please anyone help me.

like image 462
P.Lee Avatar asked Jul 11 '26 22:07

P.Lee


1 Answers

You can share the data between multiple tabs by using localStorage.

The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

You can set item in localStorage as below before window.open()

let data = {name : 'test' };
localStorage.setItem('object', JSON.stringify(data));

and when new tab is opened you can get the data object by using

let data = JSON.parse(localStorage.getItem('object'));

Note: Do not save sensitive data in localStorage.

It works on same-origin policy. So, data stored will only be available on the same origin.

like image 75
Ankit Prajapati Avatar answered Jul 14 '26 13:07

Ankit Prajapati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!