[(appfocused)]="isFocused"
のような双方向バインドをサポートするプロパティを持つディレクティブを実装しようとしています。コンポーネントは要素にフォーカスするためにisFocused
プロパティをtrueに設定できますが、要素がフォーカスを失ったら変数はfalseに戻されます。双方向バインディングの出力部分がカスタムディレクティブで機能しない
私はバインディングのこの種を実装するための鍵は同じですが、Change
接尾辞出力1と名付け@Input
と@Output
のための2つのプロパティを持つていること(hereとhere)読みました。これはこれまでの私の実装です(TypeScript):
@Directive({
selector: '[appfocused]'
})
export class FocusedDirective implements OnChanges, AfterViewInit {
@Input('appfocused')
focused: boolean;
@Output('appfocused')
focusedChange: EventEmitter<boolean> = new EventEmitter();
constructor(private elementRef: ElementRef, private renderer: Renderer) { }
ngAfterViewInit() {
this.renderer.listen(this.elementRef.nativeElement, 'blur',() => {
this.setFocused(false);
});
}
ngOnChanges() {
if (this.focused) {
setTimeout(() => {
this.elementRef.nativeElement.focus();
}, 0);
}
}
private setFocused(value: boolean) {
this.focused = value;
this.focusedChange.emit(this.focused);
console.log('focused set to ' + value);
}
}
入力プロパティはうまく動作しますが、出力プロパティを動作させることができません。 console.log
コールのおかげで、focusedChange.emit()
行がヒットしていますが、プロパティがバインドされている値には影響しません。
Here is a working example (plunker).はisFocused
プロパティの値を表示し、設定するダミー部品含ま:フォーカスリンクを押す
@Component({
selector: 'my-app',
template: `
<div>
<textarea [(appfocused)]="isFocused"></textarea>
</div>
<a (click)="focus()" href="#">Focus</a>
{{isFocused}}
`,
})
export class App {
isFocused = false;
focus() {
this.isFocused = true;
}
}
を予想通りtextarea
に焦点を当てています。ただし、それをクリックしてもisFocused
変数はリセットされません。リンクをもう一度押しても効果はありません。isFocused
の値はすでに真であるため、Angularは変更を検出しません。
私には何が欠けていますか?
感謝を!どういうわけか私はこのルールが変数の名前にのみ適用されていると思っていた... – kamilk
うん、それはときどき混乱することがあります - 私は通常、そのようなあいまいさの可能性を制限するために属性と変数の名前を同じにしておきます –