2016-12-27 6 views
-1

をループするときどのように私のコンポーネントの構造は、この角度2 - どのように内部のコンポーネントに値を渡す

Parent.ts

@Component({ 
    template: ` 

      <div *ngFor="let i of optionCollection; let index = index; trackBy: trackByFn"> 
       <Child></Child> 
       <button type="submit" class="btn btn-primary">Create</button> 
      </div> 

    `, 
}) 
export class Parent { 

} 

Child.ts

@Component({ 
    selector: 'Child' 
    template: ` 
     <input /> 
    `, 
}) 
export class Child { 
    indexValueFromParent:any 
} 

のようなものです親のインデックス値を子コンポーネントに渡し、その値を子のvarに割り当てます。indexValueFromParent

+0

使用viewChild https://angular.io/docs/を始める必要がありますts/latest/cookbook/component-communication.html#!#親からビューへの子 –

答えて

4
@Component({ 
    selector: 'Child' 
    template: ` 
    <input /> 
    `, 
}) 
export class Child { 
    @Input() indexValueFromParent: number; 
} 

@Component({ 
    template: ` 

     <div *ngFor="let i of optionCollection; let index = index; trackBy: trackByFn"> 
      <Child [indexValueFromParent]="index"></Child> 
      <button type="submit" class="btn btn-primary">Create</button> 
     </div> 

    `, 
    }) 
    export class Parent { 

    } 
-1

あなたはおそらくしたいと思うどのようなことは持つEventEmitterを使用して、あなたにそれをネクタイで子コンポーネントこれにより、子コンポーネントにイベントを作成し、親コンポーネントのイベントに反応することができます。たとえば下にあなたは

@Component({ 
    template: ` 
     <div class="container"> 
      <input /> 
      <MyInput (myEvent)="handlEvent(data)"></MyInput> 
      <MyInput (myEvent)="handlEvent(data)"></MyInput> 
     </div> 
    `, 
}) 
class ParentComponent { 
    handleEvent(data) { 
     console.log(data.hour, data.minute); 
    } 
} 

子供

@Component({ 
    selector: 'MyInput', 
    template: ` 
     <input [(ngModel)]="hour" (ngModelChange)="inputChange($event)" type="number" name="hour" /> 
     <input [(ngModel)]="minute" (ngModelChange)="inputChange($event)" type="number" name="minute" /> 
    ` 
}) 
class ChildComponent { 
    public myEvent: EventEmitter; 
    public hour; 
    public minute; 

    constructor() { 
     this.myEvent = new EventEmitter(); 
    } 

    inputChange(e) { 
     this.myEvent.emit({hour: this.hour, minute: this.minute}); 
    } 
} 

詳細はhttps://angular.io/docs/ts/latest/api/core/index/EventEmitter-class.htmlをチェック

関連する問題