首页 文章

如何在Angular Material 2中构建自定义组件

提问于
浏览
6

是否有任何标准方法可以在Angular Material 2之上构建自己的组件,或者通过扩展现有组件 .

之前我使用过Sencha / ExtJS框架,通过扩展它在顶级EXTJS基础组件上构建自己的组件非常简单 .

我查看了Angular Material 2 CDK,但没有关于如何在其上构建自定义组件的文档 .

2 回答

  • 1

    这个article提供了关于CDK的出色解释和示例 .

    CDK的目标是为开发人员提供更多工具来为Web构建出色的组件 . 这对于想要在不采用Material Design可视语言的情况下利用Angular Material功能的项目特别有用 .

    您可以使用CDK扩展组件,但是,我知道只有一些组件可用,即 overlaysteppertable . 据我所知,更多的材料组件将进入CDK内部以将其作为基础 .

    目前,您无法修改material2组件的行为,但是,您可以覆盖样式以查看所需内容 . 您需要使用ViewEncapsulation来实现这一目标 .

    例如,如果要自定义 <md-tab> 样式,可以执行以下操作:

    Changes in Typescript code:

    import {Component, ViewEncapsulation} from '@angular/core';
    
    @Component({
      ....
      encapsulation: ViewEncapsulation.None
    })
    

    Component styles css:

    /* Styles for tab labels */
    .mat-tab-label {
        min-width: 25px !important;
        padding: 5px;
        background-color: transparent;
        color: red;
        font-weight: 700;
    }
    
    /* Styles for the active tab label */
    .mat-tab-label.mat-tab-label-active {
        min-width: 25px !important;
        padding: 5px;
        background-color: transparent;
        color: red;
        font-weight: 700;
    }
    
    /* Styles for the ink bar */
    .mat-ink-bar {
        background-color: green;
    }
    

    链接到working demo .

  • -4

    你需要angular-cli才能做到这一点 . 第一个命令是

    $ ng g m customComponent
    

    这将创建一个模块 . 然后

    $ ng g c customComponent
    

    这将创建一个组件(您可以重命名) . 在模块的装饰器中,在 imports 级别添加 exports 属性:

    exports: [CustomComponentComponent]
    

    现在,创建您的组件,当您想在任何地方使用它时,只需在相关模块中导入 CustomComponentModule 即可 .

相关问题