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
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);
};
}