您可以使用类创建一些单独的指令。
例如:我的页面中有一个按钮,并且有可能的状态:default、primary、danger 和 fluid。按钮可以有许多不同的状态,但是由于代码量很大,我将向您展示这三种状态。那么让我们开始吧!
button.ts
//default button
@Directive({
selector: '[appButtonDefault]'
})
export class ButtonDefaultDirective {
// the name of the field is not important
// if you put this directive to element,
// this element will have the class called 'button--default'
@HostBinding("class.button--default")
private defaultClass: boolean = true;
}
//primary button
@Directive({
selector: '[appButtonPrimary]'
})
export class ButtonPrimaryDirective {
// the name of the field is not important
// if you put this directive to element,
// this element will have the class called 'button--primary'
@HostBinding("class.button--primary")
private primaryClass: boolean = true;
}
// danger button
@Directive({
selector: '[appButtonDanger]'
})
export class ButtonDangerDirective {
// the name of the field is not important
// if you put this directive to element,
// this element will have the class called 'button--primary'
@HostBinding("class.button--danger")
private dangerClass: boolean = true;
}
@Directive({
selector: '[appButtonFluid]'
})
export class ButtonFluidDirective {
// the name of the field is not important
// if you put this directive to element,
// this element will have the class called 'button--primary'
@HostBinding("class.button--fluid")
private fluidClass: boolean = true;
}
// you need to also create a component class,
// that import styles for this button
@Component({
//just put created selectors in your directives
selector: `[appButtonDefault], [appButtonPrimary],
[appButtonDanger], [appButtonFluid]`,
styleUrls: ['<-- enter link to your button styles -->'],
// it is required, because the content of <button> tag will disappear
template: "<ng-content></ng-content>"
})
export class ButtonComponent {}
// you don't have to do it, but I prefet to do it
@NgModule({
declarations: [
ButtonDefaultDirective,
ButtonPrimaryDirective,
ButtonDangerDirective,
ButtonFluidDirective,
ButtonComponent
],
exports: [
ButtonDefaultDirective,
ButtonPrimaryDirective,
ButtonDangerDirective,
ButtonFluidDirective,
ButtonComponent
]
})
export class ButtonModule {}
不要忘记将ButtonModule 导入到您的app.module.ts 文件中。这很重要。
app.component.html
<!-- This button will have the class 'button--default' -->
<button appButtonDefault>Default button</button>
<!-- But this button will have the class 'button--primary button--fluid' -->
<button appButtonPrimary appButtonFluid>Primary and fluid</button>
希望对你有帮助。