【问题标题】:Use styling for ng-content from template component使用模板组件中的 ng-content 样式
【发布时间】:2019-06-18 11:31:48
【问题描述】:

我创建了一个模板案例组件,打算用于多个案例。要将组件用作模板,我使用了ng-content select=""

它工作正常,但并不完全符合要求。例如:

  • 我有一个带有背景图片的 div,它的样式是在模板组件内部配置的:
<div class="front-image min-vh-100 min-vw-100" [style.transform]="'scale(' + scale + ')'">
</div>

为了使其可用作模板,我将给定的代码替换为:&lt;ng-content select=".front-image"&gt;&lt;/ng-content&gt;,并在另一个组件中使用模板,如下所示:

<app-case-template *ngIf="cases[3] as case">

  <div class="front-image min-vh-100 min-vw-100" [ngStyle]="{ 'background-image': 'url(' + case.image + ')'}"
       [style.transform]="'scale(' + scale + ')'">
  </div>

</app-case-template>

如何让模板始终从模板组件中获取样式 - 现在我必须在新组件中声明其样式才能使其正常工作。另外[style.transform] 停止工作。

有没有类似绕过的东西?

【问题讨论】:

    标签: html css angular typescript


    【解决方案1】:

    您可能会以错误的方式处理此问题。我将尝试概述一个很好的方法来做到这一点。首先,为您的模板创建一个目录:

    templates - template.component.css (generic styling) - template.component.html (your markup) - template.component.ts (your ts/js)

    设置您的template.ts 以供使用:

    import {Component} from '@angular/core';
    
    @Component({
      selector: 'template-component',
      templateUrl: 'template.component.html'
      styleUrls: ['./template.component.css']
    })
    export class TemplateComponent {
    
    }
    

    在您的component.module.ts(或任何您可能称呼它的名称)中注册:

    ...
    import {TemplateComonent} from './templates/template.component';
    ...
    const exportedComponents = [
       SvgIconComponent
    ]
    

    如果需要,让您的shared.module.ts 导出它:

    import {ComponentsModule} from './components/components.module';
    ...
    exports: [ComponentsModule]
    

    现在您可以像使用自定义 HTML 标记(您的选择器)一样使用它:

    <template-component class="template"> </template-component>
    

    现在它将始终从自身获取 css 样式,但您可以像我一样在该标记中粘贴一个自定义类,或者从主组件的样式页面中这样调用它: p>

    template-component {
       margin: 10px;
       background-color: grey;
    }
    

    您可以做很多事情,包括在模板中设置@Input() 标记,这些标记可以从您的 HTML 标记中调用。您还可以使用 Angular 绑定在其中动态输入值或文本。这里有很多选择。

    注意:不要将它们称为模板,而应考虑将它们称为共享组件或共享模式(如果是)。有一个名为shared &gt; components 的目录,并有一个custom-name 目录,其中包含用于组织的类似内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-30
      • 2017-04-26
      • 2020-05-23
      • 2020-02-21
      • 2017-08-28
      • 2018-11-04
      • 2016-07-31
      相关资源
      最近更新 更多