【问题标题】:Angular8: using different template for same componentAngular8:对同一组件使用不同的模板
【发布时间】:2019-10-14 08:40:13
【问题描述】:

我在 Angular 中有一个场景,我需要为同一个组件 ts 文件使用不同的 HTML 模板,就像这样

let templateUrl: string;
switch (environment.country) {
  case 'India':
    templateUrl = './comp1-in.component.html'
    break;
  case 'Brazil':
    templateUrl = './comp1-br.component.html'
    break;

  default:
    templateUrl = './comp1.component.html';
    break;
}

@Component({
  selector: 'app-comp1',
  templateUrl: templateUrl,
  styleUrls: ['./comp1.component.scss']
})

但这并没有按预期工作,它只是在视图中呈现模板路径而不是使用模板

【问题讨论】:

    标签: angular typescript angular8


    【解决方案1】:

    在我看来,您应该为所有组件创建一个具有可重用逻辑的基本组件,然后为每个国家/地区创建不同的组件,这些组件将扩展基本组件。

    然后在父组件中根据国家/地区插入适当的模板:

    <app-india *ngIf="env.country === Country.India"></app-india>
    <app-brazil *ngIf="env.country === Country.Brazil"></app-brazil>
    ...
    

    【讨论】:

      【解决方案2】:

      您不能使用 Switch case。您可以在同一模板上使用 ng-template 和 ngIf 来实现此目的。

      如果你想拥有不同的模板,你可以看看p3x-angular-compile

      【讨论】:

        猜你喜欢
        • 2020-11-13
        • 1970-01-01
        • 2020-04-13
        • 2017-10-27
        • 2017-03-24
        • 2019-07-06
        • 2012-11-02
        • 2011-11-09
        • 1970-01-01
        相关资源
        最近更新 更多