Reputation: 375
When a value is entered into an input and I open the window in a new tab, I would like that value to still be shown on the new tab.
Is this possible to use window.localStorage
to achieve this?
Please see Stackblitz
<input style="border: red solid 2px;" placeholder=" enter text...">
<button id="btn" style="background:red"
(click)="openNewTab()" routerLink="/{{ href }}">
Open-In-New-Tab >
</button>
export class About{
title: string = "About Page.";
public href: String = '';
constructor(private router: Router, private route:ActivatedRoute)
{ }
openNewTab() {
window.open('' + this.href + '?show=false', '_blank').focus();
}
ngOnInit() {
this.href = decodeURI(this.router.url.replace(/\/.*\//g, ''));
this.route.queryParams.subscribe(params => {
if (params.show === 'false') {
document.getElementById('navigation').outerHTML = '';
document.getElementById('btn').outerHTML = '';
}
});
}
}
Actual result: The input value disappears in the new tab.
Expected result: The newly opened tab should retain the input value
Upvotes: 2
Views: 908
Reputation: 8292
Yes indeed, you can achieve this with window.localStorage
, how ever I would suggest you to use window.sessionStorage
. I will explain why at the end of a post.
You will have to use (change)
event on input in order to save the value you entered. You will also have to add [(ngModel)]
to the <input>
Template
<input [(ngModel)]="inputValue" (change)="setValue($event.target.value)">
Component
export class MyComponent {
inputValue = '';
ngOnInit() {
this.inputValue = window.sessionStorage.getItem('savedValue');
}
setValue(value) {
window.sessionStorage.setItem('savedValue', value);
}
}
This will retain the value when you open a new tab. How ever bear in mind that the value will also be retained if you refresh the initial page. If you use sessionStorage
the value will be gone if you reopen your browser. With localStorage
that wouldn't be the case as localStorage
never expires.
If you want the value to be there ONLY when the page is reopened in a tab, I would suggest you to pass it as a Query string in URL. Then in Angular you will look if that query string exists in a URL and show the value (Either coming straight from a query string, or from storage)
Upvotes: 2