2016-02-20 37 views
9

In Angular 1 è possibile rendere obbligatorio un attributo di direttiva. Come lo facciamo in Angular 2 con @Input? I documenti non lo menzionano.Angular 2 make @Input on directive required

Es.

Component({ 
    selector: 'my-dir', 
    template: '<div></div>' 
}) 
export class MyComponent { 
    @Input() a:number; // Make this a required attribute. Throw an exception if it doesnt exist 
    @Input() b:number; 

    constructor(){ 

    } 
} 

risposta

19

Check in ngOnInit() (ingressi non sono ancora impostati quando viene eseguito il costruttore) se l'attributo ha un valore.

Component({ 
    selector: 'my-dir', 
    template: '<div></div>' 
}) 
export class MyComponent { 
    @Input() a:number; // Make this a required attribute. Throw an exception if it doesnt exist 
    @Input() b:number; 

    constructor(){ 

    } 

    ngOnInit() { 
     if(null == a) throw new Error("Attribute 'a' is required"); 
    } 
} 

Si potrebbe anche verificare in ngOnChanges(changes) {...} se i valori non sono stati impostati su null. Vedere anche https://angular.io/docs/ts/latest/api/core/OnChanges-interface.html

+0

Potrebbero Voglio anche controllare indefinito e dare un messaggio di errore specifico per quello ... se un valore viene passato dall'attributo e viene errato o non definito per qualche altro motivo, ciò richiamerà l'attenzione su questo fatto più rapidamente, il che renderà più semplice eseguire il debug. – jpoveda

+0

grazie, ma non esiste un meccanismo per quello fornito dal framework, corretto? –

+0

Corretto, attualmente nessun supporto di framework. –

4

Si può fare in questo modo:

constructor() {} 
ngOnInit() { 
    if (!this.a) throw new Error(); 
} 
2

Per quanto mi riguarda, ho dovuto fare in questo modo:

ngOnInit() { if(!this.hasOwnProperty('a') throw new Error("Attribute 'a' is required"); }

Cordiali saluti, se si desidera richiedere direttive @Output, quindi provare questo:

export class MyComponent { 
    @Output() myEvent = new EventEmitter(); // This a required event 

    ngOnInit() { 
     if(this.myEvent.observers.length === 0) throw new Error("Event 'myEvent' is required"); 
    } 
}