Nancy
Nancy

Reputation: 1011

enable/ disable button based on value entered in text box angular 4 - initial load not working

I need to enable / disable the below button and I have the below code. It works fine only from second time onwards. Initially when I land on the page, the button should be disabled because I dont have a value in the input box. If i enter something inside the text box and delete it , the button gets disabled. How do I disable the button for the first when I land on the page in angular 4

<input type="email" class="form-control" id="inputValue"  placeholder="[email protected]" formControlName="inputValue">
 <button type="button" id="verifyBtn" [disabled]="inputValue === ''" class="btn btn-primary btn-large" (click)="verify()">Verify</button>

Upvotes: 4

Views: 14906

Answers (2)

Pranay Rana
Pranay Rana

Reputation: 176906

Based on you updated question you want to disable button control when you land on page , to do that you should create your form control like as below

this.heroForm = this.fb.group({
  inputValue : ['', Validators.required ],
});

if you do as above then you control will enter in invalidate state first time itself. in your button html you should do this

<form [formGroup]="heroForm">
    <button
     type="button"
     id="verifyBtn"
     formControlName="inputValue"
     [disabled]="heroForm.get('inputValue').invlaid"
     class="btn btn-primary btn-large"
     (click)="verify()">Verify</button>
  </form>

can you try like this , so code below checks inputvalue is there or not and if inputvalue is there check that its has value or not

[disabled]="!inputValue || (inputValue && inputValue.length < 1)"

Upvotes: 2

Mavlarn
Mavlarn

Reputation: 3883

You can set input like this:

[disabled]="!inputValue"

Because the inputValue value is not set at the beginning, which is undefined, so when you check inputValue === '' it will be false

[Update based on comment]
If you use [(ngModel)], which is bi-directional, you need to be careful about the data input from view to controller, and output from controller to view. In many times, It is a bad design.

Because you use fromControlName, which is reactiveForm, you should just use reactiveForm and subscription to handle input value. You can check the post

Upvotes: 11

Related Questions