【问题标题】:Angular2 switch div contentAngular2切换div内容
【发布时间】:2018-01-30 16:33:39
【问题描述】:

我想在 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;
  }

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

【问题讨论】:

  • 这背后的目的是什么,所以我们可以建议更好的做法,因为它看起来不是很好的做法
  • 好吧..这就是你替换 html 时应该发生的事情。
  • 我要做的就是将顶部货币 div 与底部切换并保持所有功能正常工作。 500 - ZAR 顶部 div 10- 美元底部 div 我只想通过单击按钮将底部 div 移动到顶部

标签: angular binding ionic2


【解决方案1】:

您可以为每个内部内容定义一个ng-template,并将每个内容插入一个带有ngTemplateOutletng-container。在适当的时候,您可以交换两个容器的模板。这个想法显示在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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多