如何在Angular2中禁用动态表单

时间:2017-12-26 11:58:12

标签: javascript angular forms angular2-forms

我已经基于JSON的数据[字段]创建了一个动态表单,但是我需要最初禁用表单,这样当我们点击编辑时,只有表单变得可编辑。

以下是我的表格代码:

<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">

并在我的组件HTML中从上面填充开关案例:

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

4 个答案:

答案 0 :(得分:1)

最初将表单设置为禁用。

<强> component.ts

showForm?:boolean = false;

<强> component.html

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

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

答案 1 :(得分:1)

你需要做这样的事情:

<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>

答案 2 :(得分:0)

@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">

您可以使用指令解决此问题。例如,一个名为Canbedisabled的指令和一个属性“被阻止”。编写一个setter for blocked并将其设置为nativelement.disabled属性。

参考:https://github.com/angular/angular/issues/11271

答案 3 :(得分:0)

[disabled]="!isEditable"其中initialize isEditable =&#39;已停用&#39;这可以在文本和电子邮件输入字段中添加。

同样在您的修改按钮中,您可以添加回调以进行点击,您可以在其中设置isEditable =&#39;&#39;。