Anto
Anto

Reputation: 4305

Values not passed correctly from parent to child

I am new to Angular2 and for practice purposes I have created a set of 3 input components with a Reset button that erases the values entered. I wanted to test the @Input decorator and how values are passed from parent to children. The issue in my code is that the button erases the values only once

Here is the code, the parent component:

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

@Component({
  selector: 'app-root',
  template: `
    <button (click)="reset()">Reset Age</button>
  <app-form-user [age]="age" [name]="name" [surname]="surname">
    </app-form-user>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name;
  surname;
  age;

  reset(){
    this.name = '';
    this.surname = '';
    this.age = 18;
  }
}

and the app-form-user component:

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

@Component({
  selector: 'app-form-user',
  template: `
    <form>
      <div>
        <label>Name: </label>
        <input type="text" value={{name}}/>
      </div>
      <div>
        <label>Surname: </label>
        <input type="text" value={{surname}}/>
      </div>
      <div>
        <label>Age: </label>
        <input type="number" value={{age}} min="18" max="100"/>
      </div>
    </form>`,
  styleUrls: ['./form-user.component.css']
})
export class FormUserComponent implements OnInit {

  constructor() { }

  @Input() age;

  @Input() name;

  @Input() surname;

  ngOnInit() {
    this.age = 18;
  }

}

Upvotes: 1

Views: 172

Answers (2)

Vega
Vega

Reputation: 28701

You should bind changes in the parent component to the child component:

Parent HTML:

  <app-form-user [(name)]="name"></app-form-user>

Child HTML:

 <input type="text" [ngModel]= "name" (ngModelChange)="onModelChange($event)"/>

Child class:

  @Input() name;

  @Output() nameChange = new EventEmitter();
  constructor() {
  }

  onModelChange(event) {        
    this.nameChange.emit(event);
  }

Working Demo

Upvotes: 0

No&#233;mi Sala&#252;n
No&#233;mi Sala&#252;n

Reputation: 5026

Angular provide directive to bind some variable to input elements. I don't know why your reset button only works one time, but you should look at the [(ngModel)] directive from the FormsModule.

See Two-way data binding with ngModel

<form>
  <div>
    <label>Name: </label>
    <input type="text" [(ngModel)]="name"/>
  </div>
  <div>
    <label>Surname: </label>
    <input type="text" [(ngModel)]="surname"/>
  </div>
  <div>
    <label>Age: </label>
    <input type="number" [(ngModel)]="age" min="18" max="100"/>
  </div>
</form>

And don't forget to import FormsModule in your component module.

Upvotes: 1

Related Questions