在Angular中,可以使用基于模块的样式化方法来管理和应用样式。这种方法将样式与组件的模块绑定在一起,使得样式只适用于特定的组件。
以下是一个示例:
my-module
。ng generate module my-module
my-module
模块中创建一个新的组件,并命名为my-component
。ng generate component my-module/my-component
在my-component
组件的文件夹中创建一个新的样式文件,并命名为my-component.scss
。
在my-component.scss
中编写样式代码。
/* my-component.scss */
:host {
display: block;
padding: 10px;
background-color: lightgray;
}
h1 {
color: blue;
}
p {
color: red;
}
my-component
组件的TypeScript文件中引入样式文件。/* my-component.component.ts */
import { Component } from '@angular/core';
import './my-component.scss';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.scss']
})
export class MyComponentComponent {}
my-module
模块中导入并声明my-component
组件。/* my-module.module.ts */
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyComponentComponent } from './my-component/my-component.component';
@NgModule({
declarations: [MyComponentComponent],
imports: [CommonModule],
exports: [MyComponentComponent]
})
export class MyModuleModule {}
my-module
模块的地方导入并引用它。/* app.module.ts */
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MyModuleModule } from './my-module/my-module.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, MyModuleModule],
bootstrap: [AppComponent]
})
export class AppModule {}
现在,my-component
组件的样式将只应用于my-component
组件及其子组件,而不会影响其他组件。
注意:在Angular中,样式文件的命名约定是使用.scss
扩展名,但也可以使用.css
扩展名。