主机元素上的条件样式

20

我有一个组件,它的唯一作用就是渲染,像这样:

@Component({
     selector: 'my-comp',
     host: ???,
     template: `
         <ng-content></ng-content>
     `
})

 export default class MyComp {
   @Input() title: string;
   public isChanged: boolean;
 }
组件有一个"isChanged"属性,我想基于该"IsChanged"属性在宿主元素上应用样式。这是否可行?

组件有一个isChanged属性,我想根据该属性在宿主元素上应用样式。这个可行吗?

4个回答

23

您可以使用classstyle前缀来实现此操作。以下是一个示例:

@Component({
  selector: 'my-comp',
  host: {
    '[class.className]': 'isChanged'
  },
  template: `
    <ng-content></ng-content>
  `
})
export default class MyComp {
  @Input() title: string;
  public isChanged: boolean;
}

有关详细信息,请参阅Günter的答案:


1
也许简单的 '[class.className]': 'isChanged' - yurzui
@yurzui:是的,你说得完全正确!这是针对需要具有空值才能删除属性的情况;-) 我更新了我的答案。谢谢! - Thierry Templier

7

使用 @HostBinding 的解决方案

被接受的解决方案是使用 host 元数据属性,这违反了 TSLint 的规则:

TSLint: 使用 @HostBinding 或 @HostListener 而不是 host 元数据属性 (https://angular.io/styleguide#style-06-03)

可以使用 @HostBinding 来实现相同的效果:

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

@Component({
  selector: 'my-comp',
  template: `
    <ng-content></ng-content>
  `
})
export default class MyComp {
  @Input() title: string;
  public isChanged: boolean;
  @HostBinding('class.className') get className() { return this.isChanged; }
}

0
不确定你想做什么,但是像这样的代码应该足够了,你可以在其中使用ngAfterViewInitElementRef
import {AfterViewInit, ElementRef} from '@angular/core';

@Component({
   selector: 'my-comp',
   host: ???,
   template: `
     <ng-content></ng-content>
   `
})

 export default class MyComp implements AfterViewInit {
   @Input() title: string;
   public isChanged: boolean;

   constructor(private _ref: ElementRef) {}

   ngAfterViewInit() {

     var host = this._ref.nativeElement;

     if (this.isChanged) {
        host.style.width = '200px';
     }
   }
 }

如果你想在每次 isChanged 改变时都进行一些检查,你可以实现 ngDoCheck 来代替或同时使用:

ngDoCheck() {

  if (this.isChanged !== this.previousIsChanged) {

    var host = this._ref.nativeElement;

    if (this.isChanged) {
      host.style.width = '200px';
    }
  }
}

-1

我认为您想让组件触发一个事件,该事件可以被主机捕获(并可能传递一些数据)。

要实现这一点,您需要有一个@output属性,例如:

@Output() isChanged: EventEmitter<any> = new EventEmitter()

然后在你的代码中可以这样做:

this.isChanged.emit(some value to pass)

并像这样捕获它:

(isChanged)="doSomething($event)"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接