Can I call angular Component Function Inside html file of another component

时间:2018-12-19 11:19:43

标签: angular typescript

I have one CommonFunction Component which defines all common functions required for my application.. I am trying to call these functions directly from html file.. whether its possible.. how can I achieve this?..

Please have a look on below example:

common.function.ts

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 个答案:

答案 0 :(得分:0)

You need to create an instance of public type into the constructor of your component class like below -

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>

Then your method will be accessible into your template too.

PS: You are making one more mistake in code, don't use [] with {{}} together. You always one at a same time. Both are doing the same task (Binding) with different manner.

答案 1 :(得分:0)

In your home.component.ts file, you need to include Injectable inside costructor =>

constructor(public commonservice: CommonFunction){}

Then from html, you can call the fuction as=>

[disabled]='commonservice.isDealerLoggedIn()'
相关问题