Home  >  Article  >  Web Front-end  >  How to add style classes to component tags using Angular5

How to add style classes to component tags using Angular5

php中世界最好的语言
php中世界最好的语言Original
2018-05-26 15:35:561640browse

This time I will show you how to use Angular5 to add style classes to component labels. What are the precautions for using Angular5 to add style classes to component labels? The following is a practical case, let's take a look.

There are two ways to add styles to the tags of the component itself in Angular 5:

Method 1: Use the host attribute of @Component

@Component({
 selector : 'myComponent',
 host : {
  '[style.color]' : "'red'", 
  '[style.background-color]' : 'backgroundColor'
 }
})
class MyComponent {
 backgroundColor: string;
 constructor() {
  this.backgroundColor = 'blue';
 }
}

In Adding attributes in the host configuration is equivalent to the usage of binding attributes on labels.

Set style:

  1. '[style.color]': "'red'": Note that there is a single quote inside the double quotes of the red value.

  2. '[style.background-color]':'backgroundColor': This refers to the variable backgroundColor in the component.

The advantage of this method is that you can use component variables in styles.

Set class:

@Component({
 selector : 'myComponent',
 host : {
  '[class.myclass]' : 'showMyClass'
 }
})
class MyComponent {
 showMyClass = false;
 constructor() {
 }

 toggleMyClass() {
  this.showMyClass = !this.showMyClass;
 }
}

Method 2: Use: host selector in the style

@Component({
 selector : 'myComponent',
 styles : [`
  :host {
   color: red;
   background-color: blue;
  }
 `]
})
class MyComponent {}

I believe you have mastered the method after reading the case in this article , for more exciting content, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to correctly use the vuex project structure directory and configuration

How to deal with vue-router lazy loading Loading too many resources for the first time causes slowness

The above is the detailed content of How to add style classes to component tags using Angular5. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn