Aquarius_Girl
Aquarius_Girl

Reputation: 22916

How to use a global variable to enable or disable a button in Angular template driven forms?

<a #globalVar>

<input [(ngModel)] = "newTitle"
            #newBlogTitle_l = "ngModel" >

<div *ngIf = 'newBlogTitle_l.value === "" ' >
  globalVar.value = false
</div>

<button (click) = "onSave()"   [disabled] = "globalVar" > Save </button>

If there is nothing in the input box, I expect the button to remain enabled. What's the way to achieve that?

(This is just for learning purpose.)

Upvotes: 1

Views: 974

Answers (2)

Barremian
Barremian

Reputation: 31125

It is not a good idea to modify values of variables in the template. It makes it hard to maintain in the long run. Variables modifications should be almost always done in the controller.

Besides, when there is a variable bound to [(ngModel)], you can use it directly to set the state of other elements. Try the following

Controller

export class AppComponent  {
  newTitle: string;
}

Template

<input [(ngModel)]="newTitle">
<button [disabled]="newTitle">Click me</button>

Working example: Stackblitz

Upvotes: 2

Naren Murali
Naren Murali

Reputation: 56725

I think you're going for an angular JS approach, where we can define global variables in HTML and set values. Why not just write the condition on the disabled attribute as shown below

<input [(ngModel)] = "newTitle"
            #newBlogTitle_l = "ngModel" />

<div *ngIf = "newBlogTitle_l.value" >
  test
</div>

<button (click) = "onSave()" [disabled] = "newBlogTitle_l.value" > Save </button>

https://stackblitz.com/edit/angular-vgxn4t?file=src/app/app.component.html

Upvotes: 1

Related Questions