ngfor中的angular2形式

Aaron Pang |

我正在建立一个订单列表,将数量众多的产品推到Angular2的购物车中。但是,它说它找不到未定义的属性“ sku”。我相信这是在其中拥有formcontrol的问题*ngforFormContorl无法从产品获取数据。我该如何解决?

import { Component, OnInit } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { Mongo } from 'meteor/mongo';
import { ReactiveVar } from 'meteor/reactive-var';
import { Counts } from 'meteor/tmeasday:publish-counts';
import { InjectUser } from 'angular2-meteor-accounts-ui';
import { MeteorComponent } from 'angular2-meteor';
import { REACTIVE_FORM_DIRECTIVES, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { PaginationService, PaginationControlsCmp } from 'ng2-pagination';
import { GOOGLE_MAPS_DIRECTIVES } from 'angular2-google-maps/core';
import { MD_CARD_DIRECTIVES } from '@angular2-material/card';
import { MD_TOOLBAR_DIRECTIVES } from '@angular2-material/toolbar';
import { MD_INPUT_DIRECTIVES } from '@angular2-material/input';

import { Products }   from '../../../../both/collections/products.collection';
import { Product } from '../../../../both/interfaces/product.interface';
import { Carts } from '../../../../both/collections/carts.collection';
import { Cart } from '../../../../both/interfaces/cart.interface';
import { RsvpPipe } from '../../shared/rsvp.pipe';

import template from './orders-list.component.html';

@Component({
  selector: 'order-list',
  template,
  viewProviders: [PaginationService],
  directives: [MD_CARD_DIRECTIVES, MD_TOOLBAR_DIRECTIVES, MD_INPUT_DIRECTIVES, GOOGLE_MAPS_DIRECTIVES, ROUTER_DIRECTIVES, PaginationControlsCmp,REACTIVE_FORM_DIRECTIVES],
  pipes: [RsvpPipe]
})
@InjectUser('user')
export class OrderListComponent extends MeteorComponent implements OnInit {
  products: Mongo.Cursor<Product>;
  productId: string;
  productsSize: number = 0;
  pageSize: number = 10;
  curPage: ReactiveVar<number> = new ReactiveVar<number>(1);
  nameOrder: ReactiveVar<number> = new ReactiveVar<number>(1);
  location: ReactiveVar<string> = new ReactiveVar<string>(null);
  loading: boolean = false;
  user: Meteor.User;
  orderForm: FormGroup;
  cart: Cart;
  cartId: string;
  product:Product;

  constructor(private paginationService: PaginationService,private formBuilder: FormBuilder) {
    super();
  }

  ngOnInit() {
    this.paginationService.register({
      id: this.paginationService.defaultId,
      itemsPerPage: this.pageSize,
      currentPage: this.curPage.get(),
      totalItems: this.productsSize,
    });

    this.autorun(() => {
      const options = {
        limit: this.pageSize,
        skip: (this.curPage.get() - 1) * this.pageSize,
        sort: { name: this.nameOrder.get() }
      };

      this.loading = true;
      this.paginationService.setCurrentPage(this.paginationService.defaultId, this.curPage.get());

      this.subscribe('products', options, this.location.get(), () => {
        this.products = Products.find({}, {sort: { name: this.nameOrder.get() }});
        this.loading = false;
      }, true);

    this.subscribe('product', this.productId, () => {
        this.autorun(() => {
            this.product = Products.findOne(this.productId);
            this.getProducts(this.product);
          }, true);
    }, true);

});

    this.autorun(() => {
      this.productsSize = Counts.get('numberOfProducts');
      this.paginationService.setTotalItems(this.paginationService.defaultId, this.productsSize);
    });

    this.orderForm = this.formBuilder.group({
      amount: [ '', Validators.required],
    });
  }


getProducts(product:Product) {
    if (product) {
      this.products = Products.find({
        _id: {
          $eq: this.product._id,
        },
      });
    }
  }

  resetForm() {
    this.orderForm.controls['amount']['updateValue']('');
  }

  search(value: string) {
    this.curPage.set(1);
    this.location.set(value);
  }

  changeSortOrder(nameOrder: string) {
    this.nameOrder.set(parseInt(nameOrder));
  }

  onPageChanged(page: number) {
    this.curPage.set(page);
  }

  isOwner(product: Product): boolean {
    return this.user && this.user._id === product.owner;
  }

  addOrder(){
    if(this.orderForm.valid) {
      if (Meteor.userId()) {
        this.call('addProduct',this.cartId,this.product.sku,this.orderForm.value.amount,this.product.description);
      this.resetForm();
      
      } else {
        alert('Please log in to add order');
      }
    }
  }
}
<md-content flex layout="row" class="ma-products-list">
  <div layout="row" flex>
    <div flex="50">
      <div>

        <md-content class="md-padding" style="padding-top:0;">
          <pagination-controls (pageChange)="onPageChanged($event)"></pagination-controls>
          <div *ngFor="let product of products; let i = index" >
            <form [formGroup]="orderForm" (ngSubmit)="addOrder()">
          <fieldset class="form-group">
            <md-card>
              <md-card-content>
                <div layout="row">
                <h2 class="ma-name">
                  <a [routerLink]="['/product', product._id]">{{product.name}}</a>
                </h2>
                <p class="ma-description" style="padding:0 10px;margin-bottom:35px;margin-top: 6px;">
                  {{product.description}}
                </p>
                <span class="ma-sku" >{{product.sku}}</span>
                <span class="ma-price" >{{product.price}}</span>
                <span  class="ma-unit" >{{product.unit}}</span>
                <span class="ma-limit" >{{product.limit}}</span>
                <md-input formControlName="amount" placeholder="Amount"></md-input>
                    <button md-raised-button type="submit" >Add</button>   
                    </div>
                  </md-card-content>
                </md-card>
                </fieldset>
             </form>
              </div> 
        </md-content>
      </div> 
    </div>
  </div>
</md-content>

潘卡·帕克(Pankaj Parkar)

product可在*ngFor&的每次迭代中使用,并且永远不会在this.product内部使用Component因此,您应该product像在addOrder方法的参数中那样传递对象

(ngSubmit)="addOrder(product)"

然后在addOrder方法中使用传递的产品参数

addOrder(product: any){
    if(this.orderForm.valid) {
      if (Meteor.userId()) {
        this.call('addProduct',this.cartId,product.sku,this.orderForm.value.amount,product.description);
      this.resetForm();

      } else {
        alert('Please log in to add order');
      }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章