簡體   English   中英

Angular 2:如何從指令調用 function 到組件?

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

Angular web 應用程序,添加了“全屏” package 並用於 header 工作正常。 但是當我習慣於特定的頁面形式時,它會顯示錯誤。 我們不能使用特定頁面嗎?

錯誤圖片

在此處輸入圖像描述

指示

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

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

成分

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

export class ReportComponent implements OnInit {

@ViewChild(ToggleFullscreenDirective) appToggleFullscreen = null;

  constructor() {}

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

我收到錯誤“core.js:6150 ERROR TypeError: Cannot read property 'onClick' of undefined”

this.appToggleFullscreen未定義,因為您沒有在 html 中調用它。

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

你必須這樣做,

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

堆棧閃電戰

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM