2016-12-27 66 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 /最新/菜譜/組件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