簡體   English   中英

Angular 4反應形式-FormArray中的FormArray無法獲取路徑

[英]Angular 4 reactive form - FormArray Within FormArray unable to get path

幾天來,我一直在嘗試創建一種表格,以使用戶能夠創建產品,並同時允許產品的變化形式(可能與母產品具有不同的價格)。 例如,大型小工具為10英鎊,小型小工具為5英鎊。 每次我最終得到的都是FormArray中的一個FormArray,換句話說,我有一個帶有一系列變體的產品,這些變體具有價格,但也具有一系列屬性。 問題出在我嘗試添加控件時,我可以讓變化價格很好地顯示出來,但是我無法獲得添加變化的路徑。歸因控件,我只得到關於ngFor的錯誤信息數組不是[Object,Object]或control為null ...我犯的錯誤多於我的記憶! 無論如何,到我的代碼上,這些代碼已經被大量重寫,可能比開始時還差!

首先在我的oninit中的形式:

ngOnInit() {
    this.getAttributes(); // Get Attribute Categories      
    this.form = this.fb.group({
        name: [''],
        price: [''],
        description: [''],
        stockRef: [''],
        attributes: this.fb.array([{
            attributeCategoryId: [''],
            name: [''],
        }]),
        variations: this.fb.array([{
            vprice: this.vprice,
            vattributes: this.vattributes
        }]),
    });
}

用於添加和刪除主產品屬性的部分,效果很好:

addAttribute(id: any, name: any) {
    if (!id.value || !name.value)
        return;
    this.attributes = <FormArray>this.form.get('attributes');
    var newAttribute = this.fb.group({
        attributeCategoryId: [id.value],
        name: [name.value],
    });
    this.newlist.push({ name: [name.value].toString(), attributeCategoryId: [id.value].toString() });
    this.attributes.push(newAttribute);

    id.value = '';
    name.value = '';
}
removeAttr(i: any) {
    this.attributes.removeAt(i);
    this.list2 = [];
    this.newlist.splice(i, 1);
}

我在其中添加變體的部分起作用了,但它仍然具有用於嘗試將添加到主產品中的屬性復制到變體中的代碼,我認為這是可行的,但無法訪問其中的值為了顯示它們,variant.attributes不適用於該路徑。

initVariation() {
    let v = this.fb.group({
        price: [''],
        vattributes: this.attributes //COPIES main attributes            
    });
    this.attributes.reset(); //Reset the main attributes as they now      
    return v;                //belong to a variation 
}
addNewVar() {
    const control = <FormArray>this.form.controls['variations'];
    control.push(this.initVariation());

}

在變體中添加屬性的部分,該部分不起作用,也是我component.ts中遇到問題的地方

addAttrRow() {
    const control = <FormArray>this.form.controls['variations.vattributes']
    control.push(this.initVattr())
}
initVattr() {
    let va = this.fb.group({
        vattributeCategoryId: [''],
        vname: ['']
    })
    return va;
}

最后,我的html更是一團糟:

<h1>New Product</h1>
<form [formGroup]="form" (ngSubmit)="save()">
    <div class="row">
        <div class="col-md-6 col-sm-12">
            <div class="form-group">
                <label>Product Name</label>
                <div *ngIf="!form.get('name').valid" class="alert alert-danger">
                    {{ form.get('name').getError('remote') }}
                </div>
                <input [(ngModel)]="name" type="text" formControlName="name" class="form-control">
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-6 col-sm-12">
            <div class="form-group">
                <label>Price</label>
                <div *ngIf="!form.get('price').valid" class="alert alert-danger">
                    {{ form.get('price').getError('remote') }}
                </div>
                <input [(ngModel)]="price" type="number" formControlName="price" class="form-control">
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-6 col-sm-12">
            <div class="form-group">
                <label>Product Description</label>
                <div *ngIf="!form.get('description').valid" class="alert alert-danger">
                    {{ form.get('description').getError('remote') }}
                </div>
                <textarea formControlName="description" class="form-control"></textarea>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-6 col-sm-12">
            <div>
                <h4>Attributes</h4>
                <div class="form-inline" >
                    <div class="form-group">
                        <div formArrayName="attributes">
                            <select #ac name="attributeCategoryId">
                                <option value="" selected>Category</option>
                                <option *ngFor="let a of attriblist;let i = index" value="{{a.id}}">{{a.name}}</option>
                            </select>
                            <input #a name="name" placeholder="Attribute name" />
                        </div>
                    </div>
                    <button type="button" class="btn btn-default" (click)="addAttribute(ac,a)">Add Attribute</button>
                </div>
                <br>
                <table class="table-bordered table table-striped">
                    <thead>
                        <tr>
                            <th>Attr. Category</th>
                            <th>Attr.</th>
                            <th><button type="button" (click)="addNewVar()" class="btn btn-primary">Add Variation</button></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr *ngFor="let a of form.value.attributes; let i = index;"  >
                            <td *ngIf="i > 0">{{a.attributeCategoryId}}</td>
                            <td *ngIf="i > 0">{{a.name}}</td>
                            <td *ngIf="i > 0"><button (click)="removeAttr(i)" class="btn btn-danger">X</button></td>
                        </tr>
                    </tbody>
                </table>

            </div>
        </div>
    </div>
    <!--Variations Start-->
    <div class="row" formArrayName="variations">
        <div *ngFor="let variation of form.controls.variations.controls; let i=index" [formGroupName]="i">
            <h5>Variation #{{ i + 1 }}</h5>
            <p></p>
            <div class="form-group">
                <label>Variation Price</label>
                <input name="vprice" style="max-width:50px" class="form-control">
            </div>
            <table>
                <thead>
                    <tr>
                        <th>Attr. Category</th>
                        <th>Attr.</th>
                        <th><button class="btn btn-success" (click)="addAttrRow()">+</button></th>
                    </tr>
                </thead>
                <tbody name="vattributes">
                    <tr *ngFor="let attribute of variation.get('vattributes'); let ii = index;">
                        <td><input type="text" name="vattributeCateforyId" /></td>
                        <td><input type="text" name="vname" /></td>
                        <td><button (click)="removeVAttr(ii)" class="btn btn-danger">X</button></td>
                    </tr>
                </tbody>
            </table>
            <button class="btn btn-danger" (click)="removeVariation(i)">Delete</button>

        </div>
        </div>
    <!--Variations End-->
    <br>
    <p>
        <button type="submit" class="btn btn-primary">Save</button>
    </p>
</form>

我發現您的代碼中有很多錯誤。

例如

1)您應該意識到,在處理來自FormArray控制時,我們不必忘記索引

所以代替

const control = <FormArray>this.form.controls['variations.vattributes'];

我們應該使用

addAttrRow(index) {
  const control = <FormArray>this.form.get(['variations', index, 'vattributes']);

2)如果您沒有為button指定類型,它將被submit為默認值。

<button class="btn btn-success" (click)="addAttrRow()">+</button>

並可能導致無法預測的情況。

因此,請嘗試指定type="button"

3)您遍歷對象

*ngFor="let attribute of variation.get('vattributes');

當您需要遍歷數組時

*ngFor="let variation of form.controls.variations.controls;

我創建了Plunker Example ,可以幫助您了解自己做錯了什么

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM