iymrahul
iymrahul

Reputation: 94

How to disable a Dynamic forms in Angular2

I have created a dynamic form based on data[fields] from JSON, but I need the form to be initially disabled, so that when we click on Edit then only form becomes editable.

Here is my code for form:

<div class="col-md-8 " [ngSwitch]="fieldInfo.dataTypeName">
<input *ngSwitchCase="'Text'" 
       class="form-control" 
       [(ngModel)]="pageInfoBeans.nameValueMap[fieldInfo.name]" 
       name="{{fieldInfo.name}}"
       [required]="fieldInfo.preRequiredInd" 
       [maxLength]="fieldInfo.fieldSize">    

<input *ngSwitchCase="'Email Address'" 
       type="email"  
       class="form-control" 
       [(ngModel)]="pageInfoBeans.nameValueMap[fieldInfo.name]" 
       name="{{fieldInfo.name}}"
       [required]="fieldInfo.preRequiredInd" 
       [maxLength]="fieldInfo.fieldSize">

and in my component HTML which populates from above switch case :

<app-form class="" [fieldInfo]="fieldItem.fieldInfo" [pageInfoBeans]="pageInfoBeans"></app-form>

Upvotes: 2

Views: 81

Answers (4)

Noman Yaqoob
Noman Yaqoob

Reputation: 27

You need to do something like this:

<button class='form-control' (click)='isEditable = !isEditable'>Edit Mode</button>

<div class="col-md-8 " *ngIf='isEditable' [ngSwitch]="fieldInfo.dataTypeName">
  <input *ngSwitchCase="'Text'" 
     class="form-control" 
     [(ngModel)]="pageInfoBeans.nameValueMap[fieldInfo.name]" 
     name="{{fieldInfo.name}}"
     [required]="fieldInfo.preRequiredInd" 
     [maxLength]="fieldInfo.fieldSize" />    

  <input *ngSwitchCase="'Email Address'" 
     type="email"  
     class="form-control" 
     [(ngModel)]="pageInfoBeans.nameValueMap[fieldInfo.name]" 
     name="{{fieldInfo.name}}"
     [required]="fieldInfo.preRequiredInd" 
     [maxLength]="fieldInfo.fieldSize" />
</div>

Upvotes: 1

Vijay
Vijay

Reputation: 124

@Directive({
  selector : ["canbedisabled"]
})
export class Canbedisabled{

constructor(private el: ElementRef) {

}

  @Input()
  set blocked(blocked : boolean){
    this.el.nativeElement.disabled = blocked;
  }
}

 <input formControlName="first" canbedisabled [blocked]="isDisabled">

You can solve it with a Directive. A directive named Canbedisabled and a property "blocked", for example. Write a setter for blocked and set it to nativelement.disabled property.

refer: https://github.com/angular/angular/issues/11271

Upvotes: 0

James Fooks
James Fooks

Reputation: 79

Initially set the form to disabled.

component.ts

showForm?:boolean = false;

component.html

<button (click)="showForm = !showForm">Edit</button>

<form *ngIf="showForm">
...form markup
</form>

Upvotes: 1

Vikramjit Roy
Vikramjit Roy

Reputation: 484

[disabled]="!isEditable" where initialize isEditable = 'disabled' this could be added in both the text and email input fields.

Also in your edit button you can add a callback for click where you can set isEditable = ''.

Upvotes: 0

Related Questions