Scott Hannen
Scott Hannen

Reputation: 29207

My button has a click handler, but clicking it throws an error instead of executing the function

I have a component and an HTML template. Here's the HTML:

    <button (click)="upload()"> Upload File</button>
    <upload-dialog #upload></upload-dialog>

When the button is clicked I expect it to call the upload() function in my component:

import { Component, ViewChild } from '@angular/core';
import { UploadComponent } from './upload/upload.component';

@Component({
  selector: 'app-something',
  templateUrl: './something.component.html'
})
export class SomethingComponent {
  @ViewChild('upload', { static: false }) uploadDialog: UploadComponent;

  upload(): void {
    this.uploadDialog.showUpload = true;
  }
}

(The function just calls a method in the UploadComponent.)

But instead of calling the upload() function it returns a meaningless error:

ERROR TypeError: _angular_core__WEBPACK_IMPORTED_MODULE_1__.ɵnov(...) is not a function
    at Object.handleEvent (something.component.html:8:25)
    at handleEvent (core.js:46249:77)
    at callWithDebugContext (core.js:47906:1)
    at Object.debugHandleEvent [as handleEvent] (core.js:47515:1)
    at dispatchEvent (core.js:31567:1)
    at core.js:45171:1
    at HTMLButtonElement.<anonymous> (platform-browser.js:976:1)
    at ZoneDelegate.invokeTask (zone-evergreen.js:399:1)
    at Object.onInvokeTask (core.js:41686:1)
    at ZoneDelegate.invokeTask (zone-evergreen.js:398:1)

What am I doing wrong?

Upvotes: 0

Views: 426

Answers (1)

Scott Hannen
Scott Hannen

Reputation: 29207

The child component within your component has a reference variable, #upload. It's the same as the name of the function that your button calls:

    <button (click)="upload()"> Upload File</button>
                     ^^^^^^^^
    <upload-dialog #upload></upload-dialog>
                   ^^^^^^^

That creates a conflict. One fix is to change the name of the function. Or you can change the reference variable to something else like #uploadDialog (or whatever) and also change it in in the component.ts.

@ViewChild('uploadDialog', { static: false }) uploadDialog: UploadComponent;
            ^^^^^^^^^^^^

Either way, the problem should be resolved when the reference variable and the function don't have the same name.

Upvotes: 2

Related Questions