Why is this function not running?

Viewed 92

Please excuse any key term mistakes here. Even though I have great English I learned programming in my native language.

I have a project running the latest version of Angular, using Bootstrap. I don't know if that's making a difference here or not, I'm really stumped.

I have two separate modals in my component. One of them includes a form to register some data to my DB and has a button with a function bound to it in order to save all the data. It looks something like this:

<div class="modal fade" id="addTaskModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
  aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Submit a new task</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form [formGroup]="taskForm" class="form-group">
           <!-- Form data and whatnot is in here -->
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <input type="button" value="Submit Task" class="btn btn-primary" (onclick)="submitTask()">
           <!-- ^^ This button is not running correctly -->
      </div>
    </div>
  </div>
</div>

My typescript looks like this

  submitTask() {
    console.log("test");
  }

It won't even log to the console. Usually when I call a function that isn't declared in my typescript component, the page won't render and return an error, which is fine. I tried changing the name of the function to something that didn't exist, and for some reason I didn't get an error. I got an error to my VS Code console, but the page still rendered and worked fine. Am I doing something wrong that is plainly obvious? Or is it just that I can't have two modals on one page, although that makes no sense at all?

2 Answers

You don't use the on prefix in Angular components. So it would look like this (simplified):

<button class="btn btn-primary" (click)="submitTask()">Submit Task</button>

Docs on event binding: https://angular.io/guide/event-binding

<input type="button" value="Submit Task" class="btn btn-primary" (onclick)="submitTask()">

Remove the parenthesis between onclick and change it to on-click as in <input on-click="submitTask()">.

alternatively, do (click)="submitTask()"

<button class="btn btn-primary" (click)="submitTask()">Submit Task</button>

Refer to the Event Binding docs

Related