我想在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;
}
这完成了切换,但我丢失了页面上的所有值,并且选择元素不再起作用。
您可以为每个内部内容定义一个ng-template
,并将每个内容插入到带有ngTemplateOutlet
的ng-container
中。在适当的时候,你会交换两个容器的模板。这个想法在这个堆栈闪电战中得到了体现。
在您的情况下,它将是这样的:
<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;
}
可以使用CSS仅使用 CSS 交换 DIV 位置
.container {
display:flex;
flex-direction: column-reverse;
}