如果在活动表单中删除行,我怎么能够禁用提交按钮。我很困惑,因为我可以通过编写validators.required来处理表单,但如果行被删除,如何禁用提交按钮?代码如下。
HTML
<form class="form-horizontal" [formGroup]="myForm" (ngSubmit)="onCreate()" >
<div class="card-block" formArrayName="rows">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Material SKU</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of myForm.controls.rows.controls; let i = index" [formGroupName]="i">
<td>
<select formControlName="material_id" class="col-md-10">
<option *ngFor="let mat_order of mat_orders" [ngValue]="mat_order.material_id">
{{ mat_order.sku}} - {{ mat_order.mat_name }}
</option>
</select>
</td>
<td><input type="number" class="col-md-6" formControlName="quantity"></td>
<td><input type="number" class="col-md-6" formControlName="price"></td>
<td><input type="number" class="col-md-6" formControlName="total" [ngModel] ="row.get('quantity').value * row.get('price').value"></td>
<td>
<button type="button" class="btn btn-sm btn-danger" (click)="onDeleteRow(i)"><i class="fa fa-trash-o" aria-hidden="true"></i> Remove</button>
</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-sm btn-primary float-left" (click)="initGroup()"><i class="fa fa-plus-circle" aria-hidden="true"></i> Add Row</button>
</div>
<button type="submit" class="btn btn-primary float-right" [disabled]="!myForm.valid">Save</button>
</form>
TS
initGroup() {
let rows = this.myForm.get('rows') as FormArray;
rows.push(this.fb.group({
material_id: [null, Validators.required],
quantity: [null, Validators.required],
price: [null, Validators.required],
total: [{value: '', disabled: true}, Validators.required],
}))
}
this.myForm = this.fb.group({
rows: this.fb.array([])
})
答案 0 :(得分:1)
作为问题的解决方案,如果您调用方法boolean
,则可以设置true
onDeleteRow(i)
:
deleted : boolean = false;
onDeleteRow(i){
this.deleted = true;
//...
}
在按钮中,您将检查deleted
是否为false
且行是否为空:
<button type="submit" class="btn btn-primary float-right" [disabled]="!myForm.valid || myForm.controls.rows.length == 0 || deleted ">Save</button>
希望它有所帮助:)
答案 1 :(得分:0)
与此同时
[disabled]="!myForm.valid"
你也可以把
[disabled]="!myForm.valid || myForm.pristine"
答案 2 :(得分:0)
在每个更改的值之后,检查您的表单是否有效。如果是,则将 saveButton 设置为true。 在创建表单后添加此代码:
this.myForm.valueChanges.subscribe((item: any) => {
// item is changed
if (this.form.valid) { this.saveButton = true; }
else { this.saveButton = false; }
});
在模板中 [禁用] =“saveButton”:
<button type="submit" class="btn btn-primary float-right" [disabled]="saveButton">Save</button>
答案 3 :(得分:-1)
你可以添加(在html中): {+ 1}}到你的按钮
编辑:
我以为你会定制你的条件:我的意思是,
您可以在此处添加任何条件,因此您可以添加:[disabled]="myForm.invalid"
您甚至可以为您需要的确切行为创建一个变量:例如,您可以在点击时添加Click事件:
[disabled]="myForm.invalid || myForm.controls.rows.controls.length == 0"
然后 :
(click)="onDeleteRow(i); deletedRow = true;"