2017-03-31 2 views
4

내 응용 프로그램에서 부울 구성 요소 속성을 사용하여 입력 필드를 표시하거나 숨기는 단추를 배치하려고했습니다. 버튼에 입력이 표시되면 입력에 초점을 설정해야합니다. 그러나 그것은 작동하지 않는 것 같습니다. *ngIf을 제거하면 포커스 지시문이 올바르게 작동합니다.Focus 지시어를 사용하는 Angular2 * ngIf?

내가 의미하는 것을 나타내는 plunker을 만들었습니다. 내 "문제"를 설명하는 것은 어렵습니다. 성분

HTML

<input *ngIf="filterShow.options" 
     [focus]="filterFocus.options" 
     [(ngModel)]="filter.options"> 

<button type="button" 
     (click)="setShowFilter('options')"> 
    focus 
</button> 

setShowFilter() 함수

private setShowFilter(filter: string) { 
    this.filterShow[filter] = !this.filterShow[filter]; 

    /* reset filter */ 
    this.filter[filter] = ""; 

    this.filterFocus[filter].emit(true); 
} 

focus.directive.ts

@Directive({ 
    selector: '[focus]' 
}) 
export class FocusDirective implements OnInit { 

    @Input('focus') focusEvent: EventEmitter<boolean>; 

    constructor(private elementRef : ElementRef, 
       private renderer : Renderer ) { } 

    ngOnInit() { 
    this.focusEvent.subscribe(event => { 
     this.renderer 
     .invokeElementMethod(this.elementRef.nativeElement, 'focus', []); 
    }); 
    } 
} 

답변

6

EventEmitters는 출력용 아니라 입력에있다. 대신이 같은 것을보십시오 :

@Directive({ 
    selector: '[focus]' 
}) 
export class FocusDirective implements OnChanges { 

    @Input('focus') focus: boolean; 

    constructor(private elementRef : ElementRef, 
       private renderer : Renderer ) { } 

    ngOnChanges() { 
    if (this.focus) { 
     this.renderer 
     .invokeElementMethod(this.elementRef.nativeElement, 'focus', []); 
    } 
    } 
} 
+1

이벤트 이미 터를 잘못 사용하고 있습니다. 그들은 자녀 -> 부모 의사 소통을위한 것이지 부모 - 자녀를위한 것이 아닙니다. 내가 게시 한 작품은 다음과 같다 : https://plnkr.co/edit/YtaRtA0e5L6ewxq7uCH9?p=preview – adharris

+5

'Renderer'과 그것의'.invokeElementMethod()'메소드는이 시점에서 더 이상 사용되지 않을 것이다. 'this.elementRef.nativeElement.focus()'를 직접 호출하는 것이 안전합니다. –

0

지시어를 사용하지 않고도이를 달성하기위한 청소기 방법 대신 <button><label>을 사용하고 버튼처럼 스타일을 CSS를 사용하는 것입니다. <input>가 이제 <label>에 바인딩되어 있기 때문에 예를 들어,

<label for="myInput"></label> <input id="myInput"></input>

이 방법 당신도 *ngIf의 존재에 초점을 얻을 수 있습니다. Also, Angular2 documentation website warns about the use of ElementRef because of the security vulnerability it poses.

관련 문제