developer
developer

Reputation: 1675

Inactive tab validation in ngbNav

I have a form with two tabs and a save button (outside the tab). The first tab has textbox with required validation. Somehow the "required" validation does not fire when user has opened second tab (i.e. first tab is inactive) and click on save button.

HTML Code:

<form #frm="ngForm" (ngSubmit)="onSave(frm)" >
    <button type="submit">Save</button>
    <ul ngbNav #nav="ngbNav" class="nav-tabs">
        <li [ngbNavItem]="1">
            <a ngbNavLink>Details</a>
            <ng-template ngbNavContent>
                <input type="number" class="form-control numeric" id="inputNumber" name="inputNumber"
                        [(ngModel)]="inputNumber" required />
    
            </ng-template>
        </li>
        <li [ngbNavItem]="1">
            <a ngbNavLink>Charts</a>
            <ng-template ngbNavContent>
            </ng-template>
        </li>
    </ul>
</form>

TS Code:

onSave(form) {
    if (!form.valid) { // Valid returns true when the user has opened the second tab and click on save
      return
    };
}

How can I fix this?

Upvotes: 2

Views: 1099

Answers (3)

IAfanasov
IAfanasov

Reputation: 4993

Using [destroyOnHide]="false" would be a quick fix. In a long run, it is worth considering reactive forms.

It is flexible and handles any complex scenarios. It is more component code and less HTML markup which is easier to cover with unit tests.

It takes time to master though. A few hours of training or reading the docs would be required.

Upvotes: 2

Gourav Garg
Gourav Garg

Reputation: 2911

ngbNav provide feature to keep hidden dom elements in case these are from non-active tabs. In your case, as your element is in another tab, you can keep that in DOM, which can easily be validated.

Need to use [destroyOnHide]="false" on ul (where ngbNav is added).

More Info

Upvotes: 3

Arayik
Arayik

Reputation: 144

If the tab is inactive then it's removed from DOM. So the field is not exist and it can't be validated. I would suggest you to have separate field for errors and based on that field show or hide error messages.

Upvotes: 0

Related Questions