简体   繁体   中英

Trouble using 2-way data binding in Angular

I'm working on my first Angular project, and I'm stuck at a point with two-way data binding.

app.component.html

<div>
  <table class="table table-hover">
    <thead>
      <tr>
        <th>S.no</th>
        <th>Product Name</th>
        <th>Cost</th>
        <th>Amount</th>
        <th>Tax</th>
        <th>Total</th>
      </tr>
    </thead>
    <tbody>
        <tr *ngFor="let item of shoppingList, let i=index">
          <th> </th>
          <th>{{shoppingList[i]}}</th>
          <th></th>
          <th></th>
          <th></th>
          <th></th>
        </tr>
        <tr>
          <th><button type="button" (click) ="onAddButtonClick()" class="btn btn-primary">Add</button></th>
          <th><select class="form-control">
              <option (input)="selectedItemName=$event.target.value" ngDefaultControl *ngFor="let selectedItem of getProducts()" >{{selectedItem.name}}</option>
            </select></th>
          <th></th>
          <th><input type="text" class="form-control" id="usr"></th>
          <th></th>
          <th></th>
        </tr>
    </tbody>
  </table>

</div>

app.component.ts

import { Component,Input } from '@angular/core';
import {StaticDataSourceService} from './static-data-source.service';
import {ProductRepository} from './product.repo';
import {Product} from "./product";
import {ShoppingList} from "./shoppingList";


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  public shoppingList:String[]=[];

  public selectedItem:Product =new Product();

  public selectedItemName:String;

  title = 'app';
    constructor(private repository:ProductRepository){
    }

    getProducts():Product[]{
      return this.repository.getProducts();
    }

    onAddButtonClick(){
      console.log(this.selectedItemName);
    }

    addToCart(name:String){
      this.shoppingList.push(name);
    }
}

What I am trying to achieve: I want to pass the value of the dropdown to the onAddButtonClick() method and add the value to an array(currently I'm just trying to print it). However, I keep getting the console output 'undefined'. I also was getting a number of errors and after going through a lot of posts on SO I added the ngDefaultControl which made the errors go away. What does ngDefaultControl do? Thanks in advance for both questions.

The crux of the problem is your option elements are triggering the setting of selectedItemName during their change event. You're using the input event but I think you want to be using change and you want to attach it to the select element, not individual option elements.

<select 
  class="form-control"
  (change)="selectedItemName=$event.target.value"
>
 <option *ngFor="let selectedItem of getProducts()" >{{selectedItem.name}}
  </option>
</select>

You might need to set a $watch on the select element to react to events, in lieu of the data binding

Here are the problems that I see in your code.

1.

        <tr *ngFor="let item of shoppingList, let i=index">
          <th> </th>
          <th>{{shoppingList[i]}}</th>
          <th></th>
          <th></th>
          <th></th>
          <th></th>
        </tr>

Why not use the item instead of accessing your array with the index. Something like

          <tr *ngFor="let item of shoppingList, let i=index">
              <th> </th>
              <th>{{item.something}}</th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
            </tr>
  1. The reason you are getting undefined error is because your shoppingList does not have any items! You forgot to initialize it in your constructor or ngOnInit() .

I could go on like importing ShoppingList, that look like a model for your shoppingList, but you just used shoppingList:String[] instead. Try the solution above and let me know if you still need help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM