4

Sounds so simple but I've tried quite a few things and none work.

I'm using Angular 4 and my form is template-driven:

<form #form="ngForm" novalidate>
    <label for="insz">{{ 'SEARCH_PAGE.searchInszNumber' | translate }}</label>
    <input type="text" name="insz" [placeholder]="'SEARCH_PAGE.searchInszNumber' | translate" #input required>
    <button (click)="onSearch(input.value)" ><span>{{'SEARCH_PAGE.search' | translate }}</span></button>
</form>

I want to disable the button when the (one and only) input field is empty.

2 Answers 2

7

You are missing ngModel in your input, for your input field to actually be a form control:

<input type="text" name="insz" ngModel
    [placeholder]="'SEARCH_PAGE.searchInszNumber' | translate" #input required>

and then you need to disable the button of course if form is not valid:

<button [disabled]="!form.valid" (click)="onSearch(input.value)" >Submit</button>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I had tried this before and was not working so I thought ngModel was not necessary. Then I just noticed the novalidate attribute on the form...
novalidate btw is not needed in angular 4 anymore, if you are using that. That is actually for disabling browser native validation.
Yes I'm using Angular 4! Thanks, didn't know that either.
1

You could take a look at reactive forms. I had no knowledge of them until a week ago, but they're so powerful !

This means all you need to do is add a Validator (Validators.required in your case), and add a disabled condition to your button. And that's it, you're set.

3 Comments

Thanks for the recommendation! This is rather a simple form so I thought I should use a template-driven one, but I'll give reactive forms a try as well.
I agree, they are great, but I'd say it's overkill in this scenario, where there is just one input field :)
It's never overkill. Yes, it's a bit more difficult to use them, but you have to write less code (in this case, you only need to add the validator)

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.