Angular2 @ get / set 속성으로 입력
해당 구성 요소에 Angular2 구성 요소가 있습니다. 현재 해당 속성에 바인딩 할 수 있도록 @Input ()이 적용된 묶음 필드가 있습니다.
@Input() allowDay: boolean;
내가하고 싶은 것은 실제로 get / set을 사용하여 속성에 바인딩하여 setter에서 다음과 같은 다른 논리를 수행 할 수 있다는 것입니다.
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
Angular2에서 어떻게해야합니까?
Thierry Templier 제안에 따라 변경했지만 알려진 기본 속성이 아니기 때문에 'allowDay'에 바인딩 할 수 없다는 오류가 발생합니다.
//@Input() allowDay: boolean;
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
@Input('allowDay') set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
아래 설명에 따라 setter에서 @Input을 직접 설정할 수 있습니다.
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
@Input('allowDay')
set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
이 plunkr 참조 https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview을 .
주로 setter에 논리를 구현하는 데 관심이있는 경우 :
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
// [...]
export class MyClass implements OnChanges {
@Input() allowDay: boolean;
ngOnChanges(changes: SimpleChanges): void {
if(changes['allowDay']) {
this.updatePeriodTypes();
}
}
}
SimpleChanges
입력 특성이 변경되었거나 중요하지 않은 입력 특성이있는 경우 가져 오기 가 필요하지 않습니다.
그렇지 않으면:
private _allowDay: boolean;
@Input() set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
get allowDay(): boolean {
// other logic
return this._allowDay;
}
@Paul Cavacas, 나는 같은 문제가 있었고 Input()
데코레이터를 게터 위에 설정하여 해결했습니다 .
@Input('allowDays')
get in(): any {
return this._allowDays;
}
//@Input('allowDays')
// not working
set in(val) {
console.log('allowDays = '+val);
this._allowDays = val;
}
이 플 런커를보십시오 : https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview
stackblitz의 angular 7.0.1에 대한 허용되는 답변이 여기에 있습니다. https://stackblitz.com/edit/angular-inputsetter?embed=1&file=src/app/app.component.ts
directives
더 이상 컴포넌트 데코레이터 옵션에 없습니다. 그래서 앱 모듈에 하위 지시문을 제공했습니다.
@ thierry-templier 에게 감사합니다 !
참고 URL : https://stackoverflow.com/questions/36653678/angular2-input-to-a-property-with-get-set
'development' 카테고리의 다른 글
요소의 내용이 넘치지 않는가? (0) | 2020.07.09 |
---|---|
키 목록을 통해 중첩 된 사전 항목에 액세스 하시겠습니까? (0) | 2020.07.09 |
C ++ 11에서 "auto"로 추론 할 때 람다 유형은 무엇입니까? (0) | 2020.07.09 |
사람들은 화석 DVCS에 대해 어떻게 생각합니까? (0) | 2020.07.09 |
MVC3 면도기 : 코드 블록 내에 HTML 표시 (0) | 2020.07.09 |