2

I have an Angular form inside a ng2 popup:

<popup>
  Sign up for our Newsletter!     <form #f="ngForm" (ngSubmit)="onSubmit()" novalidate>
</button>         <input type="email"/>
      <button>Submit</button>
    </form>
</popup>
<button class="submit" (click)="ClickButton()">Sign up for our Newsletter </button>

here is the onClick event function:

constructor(private popup:Popup) { }
  testAlert() {   ClickButton(){
    alert("Newsletter event works");    this.popup.options = {
  widthProsentage: 15,
  showButtons: false,
  header: "Sign up for our Newsletter!",
}
this.popup.show(this.popup.options);
  }   

It works fine but I am able to submit her even if the input is blank, how can I make so that it does not submit if it is clicked empty

I tried using RegEx but it did not work

1
  • Why do you use (ngSubmit) and (click) at the same time? where is the onSubmit func? Commented Aug 13, 2018 at 19:36

2 Answers 2

1

Consider adding validation.

Something like this:

      <div class="form-group row">
        <label class="col-md-2 col-form-label"
               for="userNameId">User Name</label>
        <div class="col-md-8">
          <input class="form-control"
                 id="userNameId"
                 type="text"
                 placeholder="User Name (required)"
                 required
                 (ngModel)="userName"
                 name="userName"
                 #userNameVar="ngModel"
                 [ngClass]="{'is-invalid': (userNameVar.touched || userNameVar.dirty) && !userNameVar.valid }" />
          <span class="invalid-feedback">
            <span *ngIf="userNameVar.errors?.required">
              User name is required.
            </span>
          </span>
        </div>
      </div>

You can then disable the submit button if the fields are not valid:

         <button class="btn btn-primary"
                  type="submit"
                  style="width:80px;margin-right:10px"
                  [disabled]="!loginForm.valid">
            Log In
          </button>
Sign up to request clarification or add additional context in comments.

Comments

0

(ngSubmit) is built-in event emitter inside of Angular ngForm and is directly related to button element which is kind of a trigger for form submission. Therefore, as lealceldeiro said, you only need onSubmit function and button intended for submission inside of your form tag.

Please provide live demo so we can see the whole file (.ts particularly). Setting the validation properly depends on what kind of forms you're going to use (template or ReactiveForms).

See more about proper ngForm usage in official documentation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.