简体   繁体   中英

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

Angular web application, added 'screen full' package and used in header worked fine. 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

<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"

this.appToggleFullscreen is undefined, because you're not calling it in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM