2016-02-20 19 views
9

W Angular 1 możemy ustawić atrybut dyrektywy wymagany. Jak to zrobić w Angular 2 przy użyciu @Input? Dokumenty o tym nie wspominają.Angular 2 make @Input na wymaganej dyrektywie

Np.

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(){ 

    } 
} 

Odpowiedz

19

Przyjazd ngOnInit() (wejścia nie są jeszcze ustalone, gdy konstruktor jest wykonywany), czy atrybut ma wartość.

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"); 
    } 
} 

Można również sprawdzić w ngOnChanges(changes) {...} jeśli wartości nie została ustawiona null. Zobacz także https://angular.io/docs/ts/latest/api/core/OnChanges-interface.html

+0

Mógłbyś również chcesz sprawdzić pod kątem niezdefiniowanym i podać konkretny komunikat o błędzie ... jeśli wartość zostanie przekazana przez atrybut, a jest ona niepoprawnie napisana lub niezdefiniowana z jakiegoś innego powodu, to zwróci na to uwagę szybciej, co ułatwi do debugowania. – jpoveda

+0

dziękuję, ale nie ma mechanizmu do tego przewidzianego przez ramy, prawda? –

+0

Prawidłowe, obecnie brak obsługi ram. –

4

Można to zrobić tak:

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

Dla mnie, musiałem zrobić to w ten sposób:

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

FYI, Jeśli chcesz wymagać dyrektyw @Output, a następnie spróbuj tego:

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"); 
    } 
}