angularangular2-templateangular2-formsangular2-ngcontent

ng-content in form tag


I have a form component with <ng-content> tag inside and btn that currently does nothing. Also I have a parent component that use it with simple input as content projection.

The problem is, whenever I click on the button, both parent and form-component are reloads, and the page refresh with the initial state.

formComponent.html:

<form class="form-control">
   <div class="form-group">
     <ng-content></ng-content>
      <button type="submit">Search</button>
   </div>
</form>

parentComponent.html:

<app-form-component>
   <input type="text" [(ngModel)]="car.id">
</app-form-component>

I feel like I'm miss something basic with content-projection.

sackblitz: https://stackblitz.com/edit/angular-zqjxjs


Solution

  • Just for suggestion, The problem is you have declared button type as submit

     <button type="submit">Search</button>
    

    So, If you declared button type as submit it will submit the form like this. I have also faced this type of problem. So just replace,

    html file

      <button type="button" (click)="doLogic()">Search</button>
    

    ts file

    doLogic(){
       //do your logics here.
    }
    

    I hope its solve your problem. Lets try this once and let me know.

    Thanks,

    Muthukumar