如果我有一个自定义组件<my-component></my-component>
我可以让它始终具有自定义属性吗?例如,<my-component data-custom-attr></my-component>
您可以使用@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 解决方案