【问题标题】:*ngIf doesn't work with ng-template (ionic 5/angular 9)*ngIf 不适用于 ng-template (ionic 5/angular 9)
【发布时间】:2020-07-13 11:39:23
【问题描述】:

这是我的 component.page.ts 文件

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-domestic',
  templateUrl: './domestic.page.html',
  styleUrls: ['./domestic.page.scss'],
})
export class DomesticPage implements OnInit {
  opchoice: string;

  constructor() { }

  ngOnInit() {
    this.opchoice = "From";
    console.log("OnInit opchoice? " + this.opchoice);
  }
  onFromToChange (ev: any) {
    console.log("OnFromToChange");
    this.opchoice = ev.detail.value;
    console.log("opchoice? >" + this.opchoice + "<");
  }
}

和 HTML 文件。

<ion-content>
  <ion-segment value="From" (ionChange)="onFromToChange($event)">
    <ion-segment-button value="From">Pickup From</ion-segment-button>
    <ion-segment-button value="To">Deliver To</ion-segment-button>
  </ion-segment>
  <div *ngIf="opchoice=='From'; then ShowFrom else ShowTo">
    <ng-template #ShowFrom class="ion-text-wrap ion-no-padding ion-no-margin">
            <ion-item>Domestic - Ship From</ion-item>
    </ng-template>
    <ng-template #ShowTo class="ion-text-wrap ion-no-padding ion-no-margin">
      <ion-item>Domestic - Ship To</ion-item>
    </ng-template>
  </div>
</ion-content>

但是,无论我单击“取件自”还是“递送至”选项卡/按钮,该页面都不会显示任何内容(它是空的)。

关于 ng-template 或 ngIf 有什么我做错或不了解的地方吗?如您所见,我正在打印 opchoice 变量的值,并且它为每种类型的点击正确打印。我曾尝试将 ngIf 放入 ion-item、离子网格和许多其他组合中,但没有任何效果。

我正在使用 Ionic 5 和 Angular 9。感谢任何帮助。

【问题讨论】:

  • 我认为你应该替换 {{ opchoice }} 而不是 opchoice
  • 只需将 ng-templates 放在与 div 相同的级别即可。您可以将这些模板包装在其他 div 中,并将别名放入 div 而不是 ng-template。它应该工作。解释:angular.io/api/common/NgIf
  • @Jinny 我试过了,各种组合都试过了,但没用。
  • @Arm144 是的,这行得通 - 就是将 ng-templates 放在与 div 相同的级别。您如何引用 Div 别名?使用 div id?
    ?顺便说一句,把这一切作为答案,我会接受的。

标签: angular9 angular-ng-if ionic5 ng-template


【解决方案1】:

正如我之前所说,您必须将 ng-templates 放在同一级别。对我来说,最干净的解决方案是:

<div class="ion-text-wrap ion-no-padding ion-no-margin">
  <div *ngIf="opchoice=='From'; else ShowTo">
    <ion-item>Domestic - Ship From</ion-item>
  </div>
  <ng-template #ShowTo>
    <ion-item>Domestic - Ship To</ion-item>c
  </ng-template>
</div>

【讨论】:

    猜你喜欢
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 2018-09-15
    相关资源
    最近更新 更多