skip to Main Content

the project I’m working on is a wordpress plugin which display an angular application. in order to do that, I prerender the angular application with Static Site Generation and put the result in the wordpress extension.

on the start of the application, I need to send the root url from wordpress to the angular application but I don’t have found how to do that.

I tried a javascript global variable :

<script>
const server = "https:/domain/directory";
</script>
<app-root></app-root>

I tried also passing the value in a tag parameter :

<app-root server="https:/domain/directory"></app-root>
<app-root [server]="https:/domain/directory"></app-root>

in all theses tries, I don’t have found how to read this value in angular.
have somebody an idea how to do that ?

2

Answers


  1. Chosen as BEST ANSWER

    I found a way of passing values.

    In html code, I set this :

    <app-root data-server="https:/domain/directory"></app-root>
    

    and to read the value in the component (app.component.ts), I use this :

    import {ElementRef, afterRender} from "@angular/core";
    
    // ...
    
    constructor(elementRef :ElementRef)
    {
        
        afterRender(() => {
            
            console.log(elementRef.nativeElement.dataset["server"]);
            
        });
        
    }
    

  2. The typical is declare a variable in your component.ts (but outside the component)

    import {CommonModule} from '@angular/common'
    ..rest of imporst..
    
    //here use declare var nameOfVariable
    
    declare var server:any;
    
    //here the definition of your component
    @Component({
      selector: '...',
      templateUrl: '...',
      styleUrls: ['..']
    })
    export class MyComponent {
     constructor(){
       //You can use the variable, see that have NO this.
       console.log(server)
     }
    }
    

    If it’s a variable that you use so much you can create in a .ts a function

    declare var server:any;
    
    function getServer():string
    {
        return server||"";
    }
    

    This allow that if you want to change the variable in the script not need look for in all yours components or services the "declare var".

    In your component or service or whatever

    import {getServer} from "./utils.ts"
    
    console.log(getServer())
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search