2017-09-08 5 views
2

私はAngular2が初めてで、練習のために、リセットボタンで入力値を消去する3つの入力コンポーネントのセットを作成しました。私は@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; 
    } 
} 

とアプリ・フォーム・ユーザー・コンポーネント:

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

} 

私のコードでの問題は、ボタンが値を消去ここでは、一度だけ

は、コード、親コンポーネントであるということですすべての歓迎は歓迎以上です!ありがとう!

答えて

1

Angularは、変数を入力要素にバインドするための指示を提供します。リセットボタンが1回だけ動作する理由はわかりませんが、FormsModule[(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> 

Two-way data binding with ngModelを参照してください。そして、あなたのコンポーネントのモジュールでFormsModuleをインポートすることを忘れないでください。

+0

リセットの成分変化(に提供される値を参照)、それは一度だけ動作しますなぜthatsの? – fubbe

+0

'' @ inputs' "age"、 "name"、 "surname"はリテラルなので、参照問題はないと思います。私は、値がHTMLの入力要素にバインドされる方法から来ていると思っています。単純な一方向バインディング –

+0

私はそれについても考えました。多分あなたは正しいです。私はドキュメントのどこかで、プロパティと属性の違い、DOMの処理方法などを覚えています。 – fubbe

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

関連する問題