简体   繁体   English

Angular 2:如何从指令调用 function 到组件?

[英]Angular 2 : How can I call function from directive to component?

Angular web application, added 'screen full' package and used in header worked fine. Angular web 应用程序,添加了“全屏” package 并用于 header 工作正常。 But when I used to particular page form it will show the error.但是当我习惯于特定的页面形式时,它会显示错误。 Cant we used particular page?我们不能使用特定页面吗?

Error Image错误图片

enter image description here在此处输入图像描述

Directive指示

import {Directive, HostListener} from '@angular/core';

declare var require: any;
const screenFull = require('screenfull');

@Directive({
    selector: '[appToggleFullscreen]'
})

export class ToggleFullscreenDirective {
    @HostListener('click') onClick() {debugger
        if (screenFull.isEnabled) {
            screenFull.toggle();
        }
    }
}

.html .html

<a href="javascript:void(0)" class="text-dark" (click)="click()">
   <app-feather-icons [icon]="'maximize'"></app-feather-icons>
 </a>

component成分

import { ToggleFullscreenDirective } from '../../../shared/directives/fullscreen.directive';

export class ReportComponent implements OnInit {

@ViewChild(ToggleFullscreenDirective) appToggleFullscreen = null;

  constructor() {}

  click() {
    this.appToggleFullscreen.onClick();
  }
}

I got error "core.js:6150 ERROR TypeError: Cannot read property 'onClick' of undefined"我收到错误“core.js:6150 ERROR TypeError: Cannot read property 'onClick' of undefined”

this.appToggleFullscreen is undefined, because you're not calling it in html. this.appToggleFullscreen未定义,因为您没有在 html 中调用它。

click() {
    this.appToggleFullscreen.onClick();
  }

You have to do it like this,你必须这样做,

<a href="javascript:void(0)" class="text-dark" (click)="click()" appToggleFullscreen>
  <span>component here</span>
</a>

stackblitz 堆栈闪电战

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在组件渲染后从指令调用函数? - How can I call function from directive after component's rendering? 如何在Angular 2中将值从父组件传递给指令? - how can I pass a value from parent component to directive in Angular 2? 我如何从Angular 2中的指令调用服务 - How can i call a service from a directive in Angular 2 我如何从代码中调用指令 ngxPrint(角度 7) - how i can to call directive ngxPrint from code (angular 7) 如何在 Angular 中保持另一个组件通用的同时从另一个组件调用一个函数? - How can I call a function from another component while keeping the other component generic in Angular? 如何在渲染的Angular 2中调用指令/组件的函数 - How to call a Directive/Component's function inside rendered Angular 2 在 angular 指令组件之外调用 function - Call function outside of angular directive component 如何从angular2的组件中调用按钮的指令onclick - how to call a directive onclick of a button from a component in angular2 我如何在 Angular 中的对话框 window 中调用基本组件上的 function - How can i call a function on a base component from a dialog window in Angular 如何从 Angular 材料对话框中调用另一个组件 function - How can I call another component function from Angular Material Dialog
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM