Angular ts - 使用ngFor中的本地数据导入组件

时间:2017-09-07 05:48:45

标签: angular typescript ngfor

我是Angular2的新手,我目前正在努力在ngFor循环中导入组件。

当您在ngFor循环中导入包含数据的组件时,它会检查.ts文件中的值,而不是ngFor中使用的局部变量。我想要做的是将ngFor中使用的变量发送到下一个组件。

accommodation.component(父视图)

TS:

import { Component, Input } from '@angular/core';
import { AccommodationModel } from '../../../../models/reservations/accommodation-model';

@Component({
    selector: 'reservations-reservation-accommodations',
    templateUrl: './accommodations.component.html'
})

export class AccommodationsComponent {
    constructor() { }

    @Input() accommodations: AccommodationModel[];
}

HTML:

<div class="card-block">
                <ngb-tabset>
                    <ngb-tab *ngFor="let accommodation of accommodations" title="{{accommodation.arrivalDate}}">
                        <ng-template ngbTabContent>
                            <div class="table-responsive">
                                <table class="table table-condensed table-bordered table-striped content-divider-up">
                                    <thead>
                                        <tr>
                                            <th>ArrivalDate</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td>
                                                {{accommodation.arrivalDate}}
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </ng-template>
                    </ngb-tab>
                </ngb-tabset>

                <reservations-reservation-accommodations-costs [costs]="accommodation.costs"></reservations-reservation-accommodations-costs>
            </div>

costs.component(子视图)

TS:

import { Component, Input } from '@angular/core';
import { CostModel } from '../../../../../models/reservations/cost-model';

@Component({
    selector: 'reservations-reservation-accommodations-costs',
    templateUrl: './costs.component.html'
})

export class CostsComponent {
    constructor() { }

    @Input() costs: CostModel[];
}

HTML:

<div class="row content-divider-up">
    <div class="col">
        {{costs.length}}
    </div>
</div>

如何将ngfor中的 let accommodation(.costs)发送到 costs.component ?使用上面的代码,cost.component中的成本总是未定义的,因为它会查找名为&#34; accommodation&#34;的变量。在accommodation.components.ts文件中,我不想要。

1 个答案:

答案 0 :(得分:0)

<reservations-reservation-accommodations-costs [costs]="accommodation.costs"></reservations-reservation-accommodations-costs>

适应是for循环的本地模板引用,并且您正在使用for循环范围之外的引用,您需要将它放在for循环中以便定义容纳< / p>