2

Can i send a variable from index.html to app.component.ts i have this script in index.html and i want to send url which is variable before removing query params to app.component.ts

  <script type="text/javascript">
        var url = window.location.toString();
       if(url.indexOf("?") > 0) {
          var sanitizedUrl = url.substring(0, url.indexOf("?"));
          window.history.replaceState({}, document.title, sanitizedUrl);
        }
      </script>

2 Answers 2

6

Of course you can. I made a small demo to show you how.

  1. All you have to do is wrap your code as you did in index.html.
  2. You have to declare the variable. You can do it inside the component as
import { Component } from '@angular/core';

// notice that foo is inited in index.html
declare var foo;

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})

or in typings.d.ts. I recommend declaring it in typings.d.ts. If you're using angular-cli, and i assume, it is located in src/app/typings.d.ts.

declare var foo: any;

And that's it. You can use your variable anywhere in the app.

Sign up to request clarification or add additional context in comments.

8 Comments

You're welcome. Please consider accepting this answer and upvoting. Thanks @Fariba
you saw in my code i want to remove query params from the url but i want to tell to app.component.ts that the url is the with query params,
in my app.component.ts i am using ActivatedRoute, to pars url, how can i pass this url to that?
ActivatedRoute is just an interface. If you want to do the redirection, I would suggest using router.navigate([url]) for it. Check more about that on official documentation. Inject Router Service through DI, and call this.router.navigate() method in you class OnInit or constructor... depends. I would also consider using APP_INITIALIZER token for this.
i do not want to do redirection, i have a website and when other frontend want to load my website they send afew query params, i want to hid query params from my address bar
|
0

Inside .html file -->

<script>
   const baseUrl = "http://0.0.0.0/";
</script>

in .ts file just declare the variable and use it -->

declare var baseUrl;
export const BASE_URL = baseUrl;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.