我可以强制 Angular 组件的所有实例都具有属性吗?

Posted

技术标签:

【中文标题】我可以强制 Angular 组件的所有实例都具有属性吗?【英文标题】:Can I force all instances of an Angular component to have an attribute? 【发布时间】:2018-11-24 09:28:08 【问题描述】:

如果我有一个自定义组件<my-component></my-component>,我可以让它始终具有自定义属性吗?例如<my-component data-custom-attr></my-component>

【问题讨论】:

【参考方案1】:

您可以通过使用@Input 来做到这一点,如果值是null,则在ngOnInit 中触发错误

Component(
    selector: 'my-component',
    template: '<div></div>'
)
export class MyComponent 
    @Input() data-custom-attr:number; // Make this a required attribute. Throw an exception if it doesnt exist
    @Input() data-custom-attr-2:number;

    constructor()

    

    ngOnInit() 
      if(null == data-custom-attr) throw new Error("Attribute 'data-custom-attr' is required");
    

src solution

【讨论】:

以上是关于我可以强制 Angular 组件的所有实例都具有属性吗?的主要内容,如果未能解决你的问题,请参考以下文章