2016-05-16 23 views
5

我有一个组件,它是所有渲染,它是这样的:主机元素有条件的造型

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

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

该组件有一个isChanged性能,我想基于主机元素上应用样式isChanged属性。这甚至有可能吗?

回答

4

您使用classstyle前缀这一点。下面是一个示例:

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

见冈特的更多细节的答案:

+1

也许简单'[class.className]':'isChanged' – yurzui

+0

@yurzui:是的,你完全正确!它的属性,你需要有一个空值来删除它;-)我更新了我的答案。谢谢! –

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'; 
    } 
    } 
} 

如果你希望每次它改变了你可以实现ngDoCheck时间做一些检查为isChanged而不是/还有:

ngDoCheck() { 

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

    var host = this._ref.nativeElement; 

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

我想你想要让你的组件火灾可以由被逮住的事件主机(并可能传递一些数据)。

要做到这一点,你将有一个@output属性,如:

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

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

this.isChanged.emit(some value to pass) 

它接住喜欢:

(isChanged)="doSomething($event)"