首页 > 解决方案 > 通过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>

标签: angulartypescriptangular6

解决方案


您可以简单地编写一个与 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 采用这种机制,这非常有用。


推荐阅读