global function in Ionic 2 / Angular 2

前端 未结 3 1684
粉色の甜心
粉色の甜心 2020-12-16 03:30

How can I setup a global function that can be accessed throughout all views?

In app.component.ts I added a simple method

  openShare() {console.log         


        
3条回答
  •  醉梦人生
    2020-12-16 04:15

    You can use Directive.

    Try as follows.

    Put the following code in separate directive file. (social-sharing.directive.ts);

    import { Directive, HostListener } from '@angular/core';
    
    @Directive({
      selector: '[socialSharing]'
    })
    export class SocialSharing {
    
      constructor() { }
    
      @HostListener('click') onClick() {
        // Your click functionality
      }
    }
    

    Import it into app.module.ts and than add to declarations.

    In HTML, just add attribute to any element which is the selector in your directive file.

    
    

    Additional Info:

    Passing values from component to directive.

    home.html

      
    

    home.component.ts

     export class HomePage {
    
       property: string = 'some url';
        constructor() {}
     }
    

    social-sharing.directive.ts

    Import Input along with others from @angular/core.

    import { Directive, Input, HostListener } from '@angular/core';
    
    @Directive({
       selector: '[socialSharing]'
    })
    
    export class SocialSharing {
      @Input('socialSharing') str: string;
    
      constructor() {}
    
      @HostListener('click') onClick() {
         console.log(this.str);
      }
    };
    
      ngAfterInit() {
         console.log(this.str);
      };
    }
    

    Using Element in Directive:

    social-sharing.directive.ts

    Import ElementRef along with others from @angular/core

     import { Directive, ElementRef, HostListener } from '@angular/core';
    
     @Directive({
       selector: '[socialSharing]'
     })
    
     export class SocialSharing {
    
       // Add ElementRef to constructor
    
       constructor(el: ElementRef) {};
    
       ngOnInit() {
          let elRef = this.el.nativeElement;
          console.log(elRef.innerHTML);        
       };
     }
    

提交回复
热议问题