代码之家  ›  专栏  ›  技术社区  ›  rahul shalgar

我可以在另一个组件的html文件中调用angular Component函数吗

  •  -2
  • rahul shalgar  · 技术社区  · 6 年前

    我有一个CommonFunction组件,它定义了我的应用程序所需的所有通用函数。。 我试图直接从html文件调用这些函数。。是否可能。。我怎样才能做到这一点?。。

    请查看以下示例:

    通用函数

    import { Injectable } from '@angular/core';
    
    
    @Injectable({
      providedIn: 'root'
    })
    export class CommonFunction {
      public static userData = JSON.parse(localStorage.getItem("userData"));
    
      public static isDealerLoggedIn(){
        if(this.userData.userType == "DEALER"){
          return true;
        }else{
          return false;
        }
      }
    }
    

    home.component.ts

    import { Component, OnInit } from '@angular/core';
    import { CommonFunction } from '../../_services/common.function';
    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.scss']
    })
    export class HomeComponent implements OnInit {
    
     constructor(){}
     ngOnInit() {
     }
    }
    

    home.component.html

    <body>
    <button class="btn btn-info" [disabled]={{CommonFunction.isDealerLoggedIn()}} type="submit">Dealer Cant Click </button>
    </body>
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Himanshu    6 年前

    在home.component.ts文件中,您需要包括可注入内部构造器=>

    constructor(public commonservice: CommonFunction){}
    

    [disabled]='commonservice.isDealerLoggedIn()'
    
        2
  •  1
  •   Pardeep Jain    6 年前

    您需要在组件类的构造函数中创建一个public类型的实例,如下所示-

    import { CommonFunction } from '../../_services/common.function';
    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.scss']
    })
    export class HomeComponent implements OnInit {
    
     constructor(
        public common: CommonFunction
     ){}
     ngOnInit() {
     }
    }
    
    <button class="btn btn-info" [disabled]='common.isDealerLoggedIn()' type="submit">Dealer Cant Click </button>
    

    PS:您在代码中又犯了一个错误,不要使用 [] 具有 {{}}