ОШИБКА Ошибка: не удается найти элемент управления с путем: «продукты -> количество»

Когда я добавляю один продукт в свою форму, покажите эту ошибку. Мой код тс:

this.products = this.ps.getProduct();

this.addform = this.fb.group({
  'invoice_number': new FormControl('', [Validators.required, Validators.nullValidator]),
  'Subtotal': new FormControl('', Validators.required),
  'products': this.fb.array([
  ]),
  'total': new FormControl('', Validators.required),
});

Класс модели:

export class Sale {
    invoice_number: number;
    products: Products[];
}

Мой HTML-код:

    <form [formGroup]="addform" (ngSubmit)="onaddsale()">
      <div class="contant">
        <div class="row">
          <div class="input-field col s4">
           <input formControlName="invoice_number" id="invoice_number" type="text" class="validate">
          </div>
    </div>
    </div>
          <tr formArrayName="products" class="group" style="cursor: pointer" *ngFor="let item of products; index as i" [formGroupName]="i">
            <td>
              <input formControlName="Subtotal" [(ngModel)]="item.Subtotal" readonly type="number" />
            </td>
            <td>
              <input formControlName="total" [(ngModel)]="item.total" readonly type="number" />
            </td>          
          </tr>
</form>

В моем HTML ничего не отображается, также покажите мою ошибку в консоли.

Не подскажете, в чем проблема, как решить?


person Community    schedule 19.03.2018    source источник
comment
Можете ли вы вставить полную ошибку консоли как часть вашего вопроса?   -  person raghav710    schedule 19.03.2018
comment
AddSaleFormComponent.html:83 ОШИБКА Ошибка: не удается найти элемент управления с путем: «продукты -> количество» в _throwError (forms.js:2432) в setUpControl (forms.js:2300) в FormGroupDirective.addControl (forms.js:6658) в FormControlName._setUpControl (forms.js:7308) в FormControlName.ngOnChanges (forms.js:7221) в checkAndUpdateDirectiveInline (core.js:12348) в checkAndUpdateNodeInline (core.js:13876) в checkAndUpdateNode (core.js:13819) в debugCheckAndUpdateNode (core.js:14712) в debugCheckDirectivesFn (core.js:14653)   -  person    schedule 19.03.2018
comment
@ raghav710 у вас есть идеи по этой проблеме?   -  person    schedule 19.03.2018
comment
Я вернусь, если найду ответ   -  person raghav710    schedule 19.03.2018
comment
Вы можете это проверить? stackoverflow.com/ вопросы/39679637/   -  person raghav710    schedule 19.03.2018
comment
@Aulonna, если вы используете реактивные формы, вы НЕ можете использовать [(ngModel)]   -  person Eliseo    schedule 19.03.2018
comment
@Eliseo Я удаляю это, мое значение добавляется в массив, но не отображается в html   -  person    schedule 19.03.2018


Ответы (2)


Попробуйте добавить formGroupName, например:

<form [formGroup]="addform" (ngSubmit)="onaddsale()">
          <div class="contant">
            <div class="row">
              <div class="input-field col s4">
               <input formControlName="invoice_number" id="invoice_number" type="text" class="validate">
              </div>
        </div>
        </div>
              <tr formArrayName="products" class="group" style="cursor: pointer *ngFor="let item of products; index as i">
             <div [formGroupName]="i">
                <td>
                  <input formControlName="subtotal" readonly type="number" />
                </td>
                <td>
                  <input formControlName="total"  readonly type="number" />
                </td>          
              </tr>
           </div>
</form>
person Sachini Witharana    schedule 09.07.2020

Более медленный, я думаю, у вас есть служба ps, у которой есть метод getProducts(), например

getProduct(id:any)
{
     return this.httpClient.get("url/"+id);
}

URL-адрес/идентификатор вернет вам json, например, например.

'invoice_number':222152
'product':[
   {item:'some',total:120,subtotal:130},
   {item:'other',total:110,subtotal:140}
]

Ну, вы должны подписаться в ngOnInit на сервис и, когда вы получите данные, создайте formGroup

ngOnInit()
{
    this.ps.getProduct('123').subscribe((data:any)=>{
        this.createform(data)
    }
}
//see that createForm is a function that return a formGroup
//this formGorup have two fields, "invoice_number" and "products"
 //products is an array. We use a function that return a array 
 //of controls and "products" is thif.fb.array(the array of controls)
createForm(data:any)
{
      return this.fb.group({
           invoice_number:[data? data.invoice_number:null,
                   [Validators.required, Validators.nullValidator]],
           products:this.fb.array(this.getProducts(data? data.products:null)
      })
}
//getProducts return an array of Controls -really an array of group controls-
getProducts(products:any)
{
   let controls[]=[];
   if (products)
   {
      products.forEach(x=>{
         controls.push(
             this.fb.group({
                  total:[x.total,Validators.required]
                  subtotal:[x.total,Validators.required]

             }
         );
      }
   }
   return controls;
}

Тогда ваш html похож на

<form [formGroup]="addform" (ngSubmit)="onaddsale()">
      <div class="contant">
        <div class="row">
          <div class="input-field col s4">
           <input formControlName="invoice_number" id="invoice_number" type="text" class="validate">
          </div>
    </div>
    </div>
          <tr formArrayName="products" class="group" style="cursor: pointer" *ngFor="let item of products; index as i" [formGroupName]="i">
            <td>
              <input formControlName="subtotal" readonly type="number" />
            </td>
            <td>
              <input formControlName="total"  readonly type="number" />
            </td>          
          </tr>
</form>

Посмотрите, что вы можете использовать this.addForm=this.createForm(), а форма имеет пустые значения. ПРИМЕЧАНИЕ: я использую «промежуточный итог» (не «промежуточный итог»), выберите использование нижнего регистра или CamelCase для именования переменных.

person Eliseo    schedule 19.03.2018
comment
Мой сервисный продукт: getProduct(prod) { return this.products; } сначала я создаю массив Product, который я хочу показать в продаже других компонентов. Эти продукты я могу показать в консоли, но не отображается в html - person ; 19.03.2018