Home > Mobile >  Passing value between ngModel
Passing value between ngModel

Time:09-26

item-list.component.html

<div *ngIf="selectedItem">
    <h2>Product Details</h2>
    <div>ID: {{ selectedItem.id }}</div>
    <div>
      Name:
      <input
        type="text"
        ngModel="{{ addCartRequest.name ===selectedItem.name}"
        disabled
      />
    </div>
</div>

item-list.component.ts

export class ItemListComponent implements OnInit {

  products: Product[]=[];
  selectedItem?: Product;

  addCartRequest: Cart= {
    id: '',
    name: '',
    quantity: 0,
    totalPrice: 0
  }
constructor(private productsService: ProductsService,private cartService: CartsService, private router: Router) { }
  ngOnInit(): void {

    this.productsService.getAllProducts()
    .subscribe({
      next: (products)=>{
        this.products = products;
      },
      error: (response) => {
        console.log(response);
      }
    });
  }

  onSelect(item:Product):void{
    this.selectedItem=item;
  }

  addCart(addCartRequest:Cart){
    this.cartService.addCart(this.addCartRequest).subscribe({
      next: (cart)=> {
        this.router.navigate(['customer/cartDetails'])
      }
    });
  }

}

I'm trying to pass value from selected-item.name to addCartRequest.name in item-list.component. Angular newbie here. The system is about a checkout system where users select items to checkout. I'm letting users select items, but I can't put them in the cart as a disabled input. Not sure if there is another way. If I put ngmodel as selectedItem.name, the value won't be sent to the cart as addCartRequest.name. I just want to show users what they have selected and send the value to the cart. How do I send the value of other ngmodel to other ngmodel?

CodePudding user response:

An input that is always disabled should be a paragraph. There's not point in using an input.

But for your question :

<input
    type="text"
    [ngModel]="selectedItem.name"
    disabled
/>

That's all you need. To update your request :

onSelect(item:Product):void{
    this.selectedItem=item;
    this.addCartRequest.name = item.name;
  }
  • Related