angular - 通过Angular 6中的指令为组件提供默认属性
问题描述
在我的 angyular 6 项目中,我想创建任何具有默认属性的组件。因为,在我的项目中总会有相同的。所以,我了解到directive
可以做到这一点。但我不知道,我怎么能写这个directive
?
例如日历
我的日历(PrimeNg)
<p-calendar [locale]="tr" dateFormat="dd/mm/yy"></p-calendar>
但是,我想要像下面这样
<p-calendar appCalendar></p-calendar>
日历指令.ts
@Directive({
selector: '[appCalendar]'
})
export class CalendarDirective {
constructor() { }
getDefaultProperties() {
var properties= { locale: 'tr', dateFormat: 'dd/mm/yy'}; ??????
return properties; ????????
};
}
我知道,我也可以通过新的自定义组件制作。但是日历有40个属性。所以,如果我像下面这样编写自定义组件,我不能使用它们中的任何一个。例如,在下面,我不能提供 minDate 或 maxDate 属性。
<my-custom-calendar>
<p-calendar [locale]="tr" dateFormat="dd/mm/yy"></p-calendar>
</my-custom-calendar>
解决方案
您可以简单地编写一个与 ng-prime 组件具有相同选择器的指令,在该指令中注入该组件,然后从那里设置默认值:
这是一个使用ng-bootstrap 进度条显示此操作的示例:
import { Directive, HostBinding } from '@angular/core';
import { NgbProgressbar } from '@ng-bootstrap/ng-bootstrap';
@Directive({
selector: 'ngb-progressbar' // same selector as the ng-bootstrap progressbar component. It could be an attribute, but then you would have to add an attribute to apply these defaults
})
export class MyProgressDirective {
constructor(bar: NgbProgressbar) { // NgbProgressbar is the actual type of the component to customize, from ng-bootstrap
bar.type = 'danger';
bar.showValue = true;
bar.animated = true;
bar.striped = true;
}
}
ng-bootstrap 有一个专门的机制来为每个组件应用自定义默认值,不过这要优雅得多。您可以建议 ng-prime 采用这种机制,这非常有用。
推荐阅读
- javascript - 使用Javascript自动单击电子中的recaptcha框
- r - 如何在 R 的“foreach”循环中转换“for 循环”?
- elixir - 带有宏的动态标识符
- reactjs - 语义 UI 反应中的中心 Menu.Item
- javascript - 如何创建 Angular 7 组件?
- javascript - 带有点击事件的 gtag 事件报告中的单引号
- ios - RxSwift Observable.empty() 正在调用 onNext
- android - 如何使用片段中的位置准确性不断更新文本视图
- react-native - 如何通过滑动来导航堆栈导航器?
- python - 如何按相关值过滤数据框列?