這裏的控制,我使用"@angular/cli": "1.2.6"
,"@angular/core": "^4.0.0"
選擇框不更新UI後清除活性形式
我想做
我試圖與功能輸入產品的反應形式是什麼。在表單內部,如果用戶點擊「添加功能」按鈕,將出現一個包含「類型」選擇框的新功能列。一旦用戶點擊功能欄內的「刪除」按鈕,該功能欄將被刪除。
我遇到了什麼問題
問題是,當我試圖在第一個和最後一個功能柱之間刪除功能列不同,FormControl成功地用正確的值更新。但是,該已刪除功能列的選擇框的UI將傳遞到即將到來的下一個功能列。
我希望有
一旦目標特徵列刪除,即將到來的功能列的UI就上去了正確的值。
樣本
1.我嘗試刪除第二個功能列。 2. formControl成功刪除了第二個功能。用戶界面中的第二個功能列已成功刪除。但是,第三個特徵列上移並用選定框的已刪除特徵的值替換空格。
我的代碼如下:
產品form.component.ts
formDOM;
features = [];
featureTypes = [
{ id: "pros", name: "pros" },
{ id: "cons", name: "cons" }];
ngOnInit() {
this.formDOM = this.formBuilder.group({
// Have other field....
feature: this.formBuilder.array([])
});
}
patchSingleFeature(feature: object): FormGroup {
let returnObject = this.formBuilder.group({
type: (feature && feature['type'])
// some other field also....
});
this.features.push("feature");
return returnObject;
}
addFeature(): void {
let featureControl = <FormArray>this.formDOM.controls['feature'];
featureControl.push(this.patchSingleFeature(new Feature()));
}
removeFeature(x: number): void {
let numberOfFeature = this.features.length;
let featureControl = <FormArray>this.formDOM.controls['feature'];
featureControl.controls.splice(x, 1);
this.features.splice(x, 1);
}
產品form.component.html
<div class="form" [formGroup]="formDOM">
<div class="col-xs-12">Features</div>
<div *ngFor="let feature of features; let x = index; ">
<feature-input [x]="x" [featureTypes]="featureTypes" [form]="formDOM" (clickEvent)="removeFeature($event)"></feature-input>
</div>
<button (click)="addFeature()">Add Feature</button>
</div>
功能-input.component.html
<div class="feature-input" [formGroup]="form">
<div formArrayName="feature">
<div [formGroupName]="x">
<select formControlName="type">
<option value="" disabled>-- Select Feature Type --</option>
<option *ngFor="let type of featureTypes" [value]="type.id">{{ type.name }}</option>
</select>
</div>
</div>
</div>
功能input.component.ts
@Input() form: FormGroup;
@Input() featureTypes: Array<object>;
@Input() x: number;
@Output() clickEvent new EventEmitter<number>();
removeFeature(x) { this.clickEvent.emit(x); }
非常感謝!它完美地工作。我可以知道我的代碼有什麼問題嗎? –
那麼,你有一些奇怪的事情,使用'features'數組。你正在從'features'數組中刪除項目,而不是實際上是formarray,所以這是'搞砸了。你根本不需要''features'數組,所以我不知道你爲什麼使用它:) – Alex
我現在明白了:P謝謝你的解釋:)在閱讀你的答案後,我發現'功能'是沒用的,哈哈 –