0

The values in my template are not getting bind to the component variables.

This is a segment of the template code:

<div class="col">
    <input class="form-control" type="text" required name="firstName" 
        [ngModel]="shipping.firstName" #firstName="ngModel">
</div>

This is the component. The inputs from the template are supposed to be bind to the shipping object of the component when the "Place Order" button is clicked in the template and the placeOrder() function logs the shipping object to the console. But the shipping object shows no value when logged.

import { Component, OnInit } from '@angular/core';

import {Shipping, Payment} from '../shared/models/data-models';

@Component({
  selector: 'app-checkout',
  templateUrl: './checkout.component.html',
  styleUrls: ['./checkout.component.css']
})
export class CheckoutComponent implements OnInit {
  private shipping:Shipping;

  constructor() { 
    this.shipping = new Shipping();
  }

  private placeOrder() {
    console.log('shipping', this.shipping)    
  }
}

This is the shipping model:

export class Shipping {
    firstName: string;
    lastName: string;
    email: string;
    phone: string;
}
2
  • 2
    You need to use [(ngModel)] instead of [ngModel] to allow 2 way binding Commented Jul 23, 2018 at 13:34
  • Yeah, you have to use the [(ngModel)], if you don't use the 2 way data binding, your changes will not be reflected. Commented Jul 23, 2018 at 14:13

1 Answer 1

2

Currently, your code is set up to only allow one way binding, as you're doing [ngModel].

To allow 2 way binding, which can update the value of shipping.firstName, you need to change it to [(ngModel)].

There is more info in the docs if you wish to read further

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.