0
votes

My component structure is like this

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 
}

How can I pass index value of the parent to the child component and assign that value to child's var indexValueFromParent

3

3 Answers

4
votes
@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
votes

As Suraj pointed out, one can use the viewChild approach. But you can also leverage the @Output decorator to emit values via events from your child component to your parent component as described here:

https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#child-to-parent

-1
votes

What you probably would want to do is use EventEmitter and tie that to your child component. This allows you to create an event in your child component and react to that in your parent component. Below example should get you started

Parent

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

Child

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

Check out https://angular.io/docs/ts/latest/api/core/index/EventEmitter-class.html for more details