Ionic 2 / Angular 2中的全局函数
如何设置可在所有视图中访问的全局函数?
在app.component.ts中我添加了一个简单的方法 openShare() {console.log("button clicked")} 然后在我的导航中我有 <button ion-button right (click)="openShare()"> <ion-icon name="md-share"></ion-icon> </button> 当我尝试从任何页面访问它时,我得到以下内容. self.context.openShare is not a function 但是如果我将它直接放在构造函数中(例如this.openShare();),它确实执行正常,但是当使用(单击)函数从任何页面调用时它就不起作用. app.component.ts不是全局的吗?我认为这是我放置它的地方,但也许我错过了一些东西. 基本上它是导航器上一个简单按钮的功能,我需要它是全局的,因为它在每个页面上使用. 任何帮助将不胜感激,仍然认为Ionic 2.
您可以使用指令.
尝试如下. 将以下代码放在单独的指令文件中. (社会sharing.directive.ts); import { Directive,HostListener } from '@angular/core'; @Directive({ selector: '[socialSharing]' }) export class SocialSharing { constructor() { } @HostListener('click') onClick() { // Your click functionality } } 将其导入app.module.ts,然后添加到声明中. 在HTML中,只需将属性添加到任何元素. <button ion-button right socialSharing> <ion-icon name="md-share"></ion-icon> </button> 附加信息: 将值从组件传递到指令. 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() {} } 社会sharing.directive.ts 从@ 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); }; } 在指令中使用元素: 社会sharing.directive.ts 从@ angular / core导入ElementRef和其他人 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); }; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |