首页 > 解决方案 > 使用 [ngTemplateOutlet] 在 ng-container 内的元素上应用类

问题描述

我有一个 PARENT 组件,它有一个 CHILD 组件。这个 PARENT 组件ng-template将被绑定到 CHILD 组件中。

为了''元素(),我使用并且它起作用了styleng-containersvgng-deep

我现在想要的是从 CHILD 组件(如)动态地将 a 添加classng-container' 元素();svgngClass

请参阅下面的代码以更好地理解。

家长

HTML:

...

<app-input [icon]="userIcon"></app-input>

...

<!-- TEMPLATES -->

<ng-template #userIcon>
    <svg>...</svg>
</ng-template>

孩子

HTML:

<ng-container *ngIf="$icon" [ngTemplateOutlet]="$icon"></ng-container>

...

打字稿:

export class InputComponent implements ControlValueAccessor {
  ...

  @Input('icon') public $icon: TemplateRef<any>;
  private color: boolean = false; // --> When this is true, apply a new class

  public onFocus(): void {
    this.color = true;
  }

  ...

SCSS:

::ng-deep {
    svg {
        transition: .3s fill;
        fill: map-get($colors, placeholder);
    }
}

标签: angular

解决方案


使用 ng-container 你可以传递上下文

<ng-container [ngTemplateOutlet]="user;context: {color: className}></ng-container>

然后你可以像在模板中一样使用它

<ng-template let-color="color">
    <div [class]="color"></div>
</ng-template>

推荐阅读