Home > Software design >  How to access variable value from ts file to html file using angular?
How to access variable value from ts file to html file using angular?

Time:06-03

front-layout.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-front-layout',
  templateUrl: './front-layout.component.html',
  styleUrls: ['./front-layout.component.css']
})
export class FrontLayoutComponent implements OnInit {

  host:any;
  constructor() { }

  ngOnInit(): void {

    this.host = "http://localhost:4200";

  }

}

front-layout.component.html

<!DOCTYPE html>
<html lang="en"><head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
    <title></title>
    <link rel="stylesheet" href="'{{ host }}'/assets/front/css/bootstrap.min.css">
    <link rel="stylesheet" href="'{{ host }}'/assets/front/plugins/select2/css/select2.min.css">
</head>
<body>
    <div >
        <router-outlet></router-outlet>
    </div>
    <script src="'{{ host }}'/assets/front/js/jquery-3.6.0.min.js"></script>
</body>
</html>

In the above code I simply declare host and try to access in my html component but it throw an error i.e. src/app/component/front/front-layout/front-layout.component.ts:5:16 - error NG2008: Could not find stylesheet file ''{{ host }}'/assets/front/css/bootstrap.min.css' linked from the template.. No idea why variable not working? Please help me.

Thank You

CodePudding user response:

I believe you should move the links and scripts to index.html, and from there, use this path

./assets/front/js/jquery-3.6.0.min.js

CodePudding user response:

To load the content of host

Must be [href] and [src] instead of href and src


and instead of href="'{{ host }}'/assets/front/css/bootstrap.min.css"


must be [href]="host '/assets/front/css/bootstrap.min.css'"

<!DOCTYPE html>
<html lang="en"><head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
    <title></title>
    <link rel="stylesheet" [href]="host   '/assets/front/css/bootstrap.min.css'">
    <link rel="stylesheet" [href]="host   '/assets/front/plugins/select2/css/select2.min.css'">
</head>
<body>
    <div >
        
    </div>
    <script [src]="host   '/assets/front/js/jquery-3.6.0.min.js'"></script>
</body>
</html>

But in angular all this stuff is done in index.html

  • Related