Angular2切换div内容

时间:2018-01-30 16:33:40

标签: angular binding ionic2

我想在angular2 / ionic2中切换两个div的内容这是我的代码。它确实切换了html,但我似乎松散了对元素的所有绑定。

<ion-list>
<div #currencyFromHtml>
  <ion-row>
    <ion-col col-8>
      <ion-item>
        <ion-input [(ngModel)]="currencyFromAmount" (ionChange)="refreshConversion()"></ion-input>
      </ion-item>
    </ion-col>
    <ion-col col-4>
      <ion-item>
          <ion-select [(ngModel)]="currencyFrom"  (ionChange)="refreshConversion()">
            <ion-option *ngFor="let c of coins; let i = index" [selected]="i==0" [value]="c">{{c.title}}</ion-option>
          </ion-select>
      </ion-item>
    </ion-col>
  </ion-row>
</div>
<ion-row>
        <button ion-button (click)="switchToAndFromCurrency()">Switch</button>
  </ion-row>
<div #currencyToHtml>
<ion-row>
    <ion-col col-8>
      <ion-item>
        <ion-input [(ngModel)]="currencyToAmount"  (ionChange)="refreshConversion()"></ion-input>
      </ion-item>
    </ion-col>
    <ion-col col-4>
    <ion-item>
        <ion-select [(ngModel)]="currencyTo" (ionChange)="refreshConversion()">
          <ion-option *ngFor="let cur of currency; let i = index" [selected]="i==0" [value]="cur">{{cur.title}}</ion-option>
        </ion-select>
    </ion-item>
  </ion-col>
  </ion-row>
</div>

运行的代码是:

    switchToAndFromCurrency()
  {

console.log(this.currencyToHtml.nativeElement.innerHTML);

  let toHtml = this.currencyToHtml.nativeElement.innerHTML;
  let fromHtml = this.currencyFromHtml.nativeElement.innerHTML;

  this.currencyToHtml.nativeElement.innerHTML = fromHtml;
  this.currencyFromHtml.nativeElement.innerHTML = toHtml;
  }

这会切换但我丢失了页面上的所有值,并且选择元素不再起作用。

1 个答案:

答案 0 :(得分:0)

您可以为每个内部内容定义ng-template,并在ng-container中使用ngTemplateOutlet插入每个内容。适当时,您将交换两个容器的模板。这个想法显示在this stackblitz

在你的情况下,它会是这样的:

<ng-template #currencyFrom>
  <ion-row>
    currencyFrom stuff here...
  </ion-row>
</ng-template>
<ng-template #currencyTo>
  <ion-row>
    currencyTo stuff here...
  </ion-row>
</ng-template>
<div>
  <ng-container [ngTemplateOutlet]="topTemplate"></ng-container>
</div>
<div>
  <ng-container [ngTemplateOutlet]="bottomTemplate"></ng-container>
</div>

使用组件代码:

@ViewChild("currencyFrom") currencyFrom: TemplateRef<any>;
@ViewChild("currencyTo") currencyTo: TemplateRef<any>;

topTemplate: TemplateRef<any>;
bottomTemplate: TemplateRef<any>;

ngOnInit(): void {
  this.topTemplate = this.currencyFrom;
  this.bottomTemplate = this.currencyTo;
}

switchToAndFromCurrency(): void {
  let temp = this.topTemplate;
  this.topTemplate = this.bottomTemplate;
  this.bottomTemplate = temp;
}