首页 > 解决方案 > 有没有办法在单个组件中控制 html pc 和 html mobile?

问题描述

我有以下代码

import { Component, OnInit } from '@angular/core';
import { mobile } from '../../../../environments/environment';

@Component({
  selector: 'ctk-details-advisory',
  templateUrl: (mobile) ? 'details-advisory.component.mobile.html' : 
'details-advisory.component.html',
 styleUrls: ['./details-advisory.component.scss'],
})
export class DetailsAdvisoryComponent implements OnInit {
// ...

这有助于我控制不同的 html、pc 和移动视图。问题是当我想执行单元测试时出现以下错误

未找到模块:错误:无法解析“(移动)?'details-advisory.component.mobile.html' : '/home/anonymous/criptoanalisis-0.2/frontend/src/app/pages/advisory/details-advisory' @ ./ src/app/pages/advisory/details-advisory/details-advisory.component.ts 23:22-121

对这个问题的一些解决方案或控制不同html的另一种方法会有很大帮助事实上我正在尝试解决这个问题我非常感谢任何建议

标签: angulartestingangular-cliangular-test

解决方案


使用单个html( details-advisory.component.html),而不是使用两个不同的模板(一个单独用于移动设备)。在component代码中,定义一个类成员

public isMobile = mobile; // imported from the environment in the import section

然后,在templatehtml 代码中,您可以使用

<ng-container *ngIf="isMobile; else desktopView">
// all html related to mobile view
</ng-container>

<ng-container #desktopview>
// all html related to desktop view
</ng-container>

推荐阅读