angular 2 - 循环时如何将值传递给内部组件

时间:2016-12-27 08:25:41

标签: angular

我的组件结构是这样的

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

3 个答案:

答案 0 :(得分: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 :(得分:-1)

正如Suraj指出的那样,可以使用viewChild方法。但您也可以利用@Output装饰器通过子组件到父组件的事件发出值,如下所述:

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

答案 2 :(得分:-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了解详情