值未从父级正确传递给子级

时间:2017-09-08 15:13:47

标签: angular typescript

我是Angular2的新手,出于练习目的,我创建了一组3个输入组件,其中包含一个Reset按钮,用于删除输入的值。我想测试@Input装饰器以及如何将值从父级传递给子级。我的代码中的问题是按钮只删除了一次

以下是代码,父组件:

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;
  }
}

和app-form-user组件:

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;
  }

}

2 个答案:

答案 0 :(得分:1)

Angular提供将某些变量绑定到输入元素的指令。我不知道为什么你的重置按钮只能运行一次,但是你应该查看[(ngModel)]中的FormsModule指令。

请参阅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>

不要忘记在组件模块中导入FormsModule

答案 1 :(得分:0)

您应该将父组件中的更改绑定到子组件:

父HTML:

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

儿童HTML:

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

儿童班:

  @Input() name;

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

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

<强> Working Demo