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

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

【问题讨论】:

    标签: angular


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 2020-06-19
      • 1970-01-01
      • 2021-08-08
      • 2015-08-08
      • 2017-09-23
      • 2011-08-01
      相关资源
      最近更新 更多