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.
<button ion-button right socialSharing>
<ion-icon name="md-share"></ion-icon>
</button>
Additional Info:
Passing values from component to directive.
home.html
<button ion-button right [socialSharing]="property">
<ion-icon name="md-share"></ion-icon>
</button>
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);
};
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…