如何在角度 2 中动态更改 :host 中的 CSS? [英] How to dynamically change CSS in :host in angular 2?

查看:73
本文介绍了如何在角度 2 中动态更改 :host 中的 CSS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何动态更改组件宿主的 CSS 属性?

我有一个组件,在它的 CSS 中我给了它一个风格:

:host {溢出-x:隐藏}

从子组件单击按钮时,我需要将 overflow-y: hidden 添加到宿主组件.

我如何实现这种行为?

解决方案

这是一个工作示例.

使用以下主机绑定:

@HostBinding('style.overflow-y') overflowY = 'scroll';

这将提供以下组件:

@Component({选择器:'我的应用',模板:`<div><按钮(点击)=addStyle()">添加样式</button><h2>你好</h2>

`,样式:[`:主持人 {溢出-x:隐藏;高度:50px;宽度:200px;显示:块;}`,],})出口类应用{名称:字符串;@HostBinding('style.overflow-y')溢出Y = '滚动';构造函数(){}添加样式(){this.overflowY = '隐藏';}}

How do I dynamically change CSS properties of a component host?

I have a component and in it's CSS I have given it a stlye:

:host {
  overflow-x: hidden
}

On a button click from child component, I need to add overflow-y: hidden to the host component.

How do I achieve this behavior?

解决方案

Here is a working example.

Use the following HostBinding:

@HostBinding('style.overflow-y') overflowY = 'scroll';

This would give the following component:

@Component({
    selector: 'my-app',
    template: `
          <div>
            <button (click)="addStyle()">Add Style</button>
            <h2>Hello</h2>
          </div>`, styles: [
        `
        :host {
          overflow-x: hidden;
          height: 50px;
          width: 200px;
          display: block;
        }
        `,
    ],
})
export class App {
    name: string;

    @HostBinding('style.overflow-y')
    overflowY = 'scroll';

    constructor() {
    }

    addStyle() {
        this.overflowY = 'hidden';
    }
}

这篇关于如何在角度 2 中动态更改 :host 中的 CSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆