如果我有自定义组件<my-component></my-component>
,我是否可以使其始终具有自定义属性?例如,<my-component data-custom-attr></my-component>
答案 0 :(得分:0)
您可以使用@Input
来执行此操作,如果值为ngOnInit
则会null
触发错误
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");
}
}