Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build custom component in Angular Material 2

Is there any standard way to build own component on top of Angular Material 2 or by extending existing component.

Earlier I used Sencha/ExtJS framework and it was quite straightforward to build own component on top EXTJS base component by extending it.

I looked into Angular Material 2 CDK but there is no documentation on it how to build custom component on top of it.

like image 941
Kanchan Avatar asked Sep 13 '17 06:09

Kanchan


People also ask

Can we customize angular material?

Angular Material supports customizing component styles via Sass API as described in the theming guide. This document provides guidance on defining custom CSS rules that directly style Angular Material components.

What is custom component in angular?

A custom element hosts an Angular component, providing a bridge between the data and logic defined in the component and standard DOM APIs. Component properties and logic maps directly into HTML attributes and the browser's event system.


1 Answers

This article provides an excellent explanation and example regarding CDK.

The goal of the CDK is to give developers more tools to build awesome components for the web. This will be especially useful for projects that want to take advantage of the features of Angular Material without adopting the Material Design visual language.

You can use CDK to extend components, however, only some components are available at the moment that I know, namely, overlay, stepper and table. As far as I know, more material components will go inside CDK to use that as base.

At the moment, you cannot modify the behavior of the material2 components, however, you can overrides the styles to look how you want. You need to make use of ViewEncapsulation to achieve that.

For example, if you want to customize <md-tab> styles, you can do the following:

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

Link to working demo.

like image 194
Faisal Avatar answered Sep 19 '22 18:09

Faisal