模板Angular 2中的绑定索引

时间:2017-08-20 16:04:04

标签: angular

我需要一个以2开头的计数器 如何链接[mdDatepicker],[mdDatepickerToggle],#next_payment _?

<div formArrayName="next_payment">
  <div *ngFor="let payment of productForm.controls.next_payment.controls; let i=index" class="panel panel-default">
    <div class="panel-heading">
      <span>Payment {{i + 2}}</span>
      <span class="glyphicon glyphicon-remove pull-right" *ngIf="productForm.controls.next_payment.controls.length > 1" (click)="removeNextPayment(i)"></span>
    </div>
    <div class="panel-body" [formGroupName]="i">
      <div class="form-group col-md-4">
        <md-input-container>
          <input mdInput [mdDatepicker]="'next_payment' + i + 2" [ngModel]="npd | date:'yyyy-MM-dd'" (ngModelChange)="npd = $event" placeholder="Date {{i + 2}}" formControlName="next_payment_date_{{i+2}}" id="next_payment_date_{{i+2}}">
          <button mdSuffix [mdDatepickerToggle]="'next_payment' + i + 2"></button>
        </md-input-container>
        <md-datepicker #next_payment_2></md-datepicker>
      </div>
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

您可以为控件定义子组件,并将i值作为属性传递。这样你仍然可以使用本地模板变量#next_payment,并为[mdDatepicker],[mdDatepickerToggle]引用它。

<强> HTML

专利组成部分:

  <div *ngFor="let payment of productForm.controls.next_payment.controls; let i=index" class="panel panel-default">
     <div class="panel-heading">
        <span>Payment {{i+2}}</span>
        <span class="glyphicon glyphicon-remove pull-right" 
               *ngIf="productForm.controls.next_payment.controls.length > 1" 
               (click)="removeNextPayment(index)"></span>
      </div>
      <my-payement-component [index]=i+2><my-payement-component>
  </div>

子组件:

<div class="panel-body" [formGroupName]="index">
    <div class="form-group col-md-4">
        <md-input-container>
            <input mdInput [mdDatepicker]="next_payment" [ngModel]="npd | date:'yyyy-MM-dd'" (ngModelChange)="npd = $event" placeholder="Date {{index}}"
                formControlName="next_payment_date" id="next_payment_date">
            <button mdSuffix [mdDatepickerToggle]="next_payment"></button>
        </md-input-container>
        <md-datepicker #next_payment></md-datepicker>
    </div>
</div>

<强>打字稿

子组件

.....
@Input() index: number;

我无法测试此代码,但我希望您明白这个想法

<强> Plunker