一个很好的方法是使用指令。我认为指令和组件之间的区别在概念上很难理解。我听说过的最好的方法是,当你想修改一个现有的DOM(文档对象模型)元素的行为时,你会使用一个指令,当你想要一个全新的DOM元素时,你将创建一个组件。否则,组件和指令几乎相同,组件只是一个带有自己的模板的指令
创建 一个指令的命令 会创建一个directive文件夹
ionic g directive ElasticHeader
关于指令的引用
selector: '[set-color]' // Attribute selector
selector: 'set-color' // Element selector
一个含input的自定义指令:
import {Directive, ElementRef, Input} from '@angular/core';
@Directive({
selector: '[set-color]' // Attribute selector
//selector: 'set-color' // Attribute selector
})
export class SetColor {
_defaultColor='pink';
//参数 setter
@Input('set-color')
set haoqihensuibianma (colorName:string) {
this.setFontColor(colorName);
};
constructor(private el:ElementRef) {
this.setFontColor(this._defaultColor);
}
setFontColor(color:string) {
this.el.nativeElement.style.color=color;
}
}
<ion-content>
<h1 set-color="#eee">
{{title}}
</h1>
</ion-content>