简体   繁体   中英

Use Component class variable inside Component host

Do you know how can I make use of a class variable inside the @Component declaration?

This is the desired approach:

@Component({
    selector: "whatever",
    host: {
        "[class]":"className"
    }
})
export class MyComponent {
    @Input() className:string="my-class-name";
}

Expected results:

<whatever class="my-class-name"></whatever>

You may want to use the HostBinding decorator to set the desired CSS class back to the host element:

@HostBinding('class.my-class-name')
protected get myClass() { 
    return true; 
}

[Edit]

The above example shows how to set a static CSS class to the host element. To set a dynamic class, then you will need to decorate the className property with HostBinding decorator:

@HostBinding('class')
@Input()
public className:string = "my-class-name";

Plunker: https://plnkr.co/edit/iPbrYbUSZtkHiGLDyo2B?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM