Search code examples
htmlangulareventsonclickcomponents

Why my "onclick()" event doesn't work in Angular?


This is my HTML code:

<div class="form-popup playerOne" id="myForm_input" dir="rtl">
    <form action="/action_page.php" class="form-container">  
      <label for="funcs"><b>انتخاب ورودی</b></label>

      <mat-select placeholder="انتخاب ورودی" >
          <mat-option *ngFor="let input of inputs" [value]="input">
            {{ input }}
          </mat-option>
      </mat-select>

        <button type="submit" class="btn " style="margin-top: 270px;" onclick="setInput($event)">اعمال</button>
        <button type="button" class="btn cancel" onclick="closeForm()">انصراف</button>
    </form>
</div>

And this is my component.ts code:

  setInput(event){
    console.log('the selected input is:' , event);
  }

But it seems it doesn't work because I don't see any log message on the console.

EDIT:

I changed my code like the following:

HTML:

<div class="form-popup playerOne" id="myForm_input" dir="rtl">
    <form action="/action_page.php" class="form-container">  
      <label for="funcs"><b>انتخاب ورودی</b></label>

      <mat-select placeholder="انتخاب ورودی" [(ngModel)] = "selectedValue">
          <mat-option *ngFor="let input of inputs" [value]="input">
            {{ input }}
          </mat-option>
      </mat-select>

        <button type="submit" class="btn " style="margin-top: 270px;" (click)="setInput(selectedValue)">اعمال</button>
        <button type="button" class="btn cancel" onclick="closeForm()">انصراف</button>
    </form>
</div>

TS:

  selectedValue: any;
  setInput(){
    console.log('the selected input is:' , this.selectedValue);
  }

But I get this error message:

FlowComponent.html:8 ERROR Error: If ngModel is used within a form tag, either the name attribute must be set or the form
      control must be defined as 'standalone' in ngModelOptions.

      Example 1: <input [(ngModel)]="person.firstName" name="first">
      Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">
    at Function.missingNameException (forms.js:5421)
    at NgModel._checkName (forms.js:5928)
    at NgModel._checkForErrors (forms.js:5905)
    at NgModel.ngOnChanges (forms.js:5803)
    at checkAndUpdateDirectiveInline (core.js:27784)
    at checkAndUpdateNodeInline (core.js:38472)
    at checkAndUpdateNode (core.js:38411)
    at debugCheckAndUpdateNode (core.js:39433)
    at debugCheckDirectivesFn (core.js:39376)
    at Object.eval [as updateDirectives] (FlowComponent.html:12)

Solution

  • In your html

    <button
      type="submit"
      class="btn"
      style="margin-top: 270px;"
      (click)="setInput()">اعمال</button>
    

    In your component use

    setInput(){
      console.log('the selected input is:' , this.selectedValue);
    }
    

    Regards