2017-06-23 9 views
1

私は角度アプリケーションでいくつかのカスタムフォームコントロールコンポーネントを実装しています。これはControlValueAccessorインターフェイスを実装していて、うまく機能します。カスタムフォームコントロールが角で初期状態としてマークされていることをどのように知ることができますか?

親フォームで、または私のカスタムコントロールで直接呼び出すと、私はその状態を更新する必要があります:私のカスタムコントロールは実際に内部コントロールを持っていますので、markAsPristine()も呼び出す必要があります。

だから、markAsPristine()が私のコントロールで呼び出されたときはどうすればわかりますか?

ControlValueAccessorインターフェイスには、この問題に関連する実装可能なメンバーがありません。

+0

[** statusChanges **](https://angular.io/api/forms/AbstractControl#statusChanges)? – developer033

+1

ドキュメントによると、 'statusChanges'オブザーバブルは、検証状態が変わったときに出ますが、私は汚れた/元の状態の変化を探しています。 –

+0

あなたは絶対に正しいです。私はあなたが本当に欲しいものを理解していないほど速く読んだ。まあ、AFAIKでは 'markAs- *'メソッドが呼び出されているかどうかわかりません。 – developer033

答えて

1

徹底的な調査の結果、この機能がAngularによって具体的に提供されていないことがわかりました。これについては私はposted an issueを公式リポジトリに持っており、機能要求ステータスが得られています。近い将来に実装されることを願っています。それまで


は、ここに2つの回避策です:

モンキー・パッチ適用このソリューションがあり得ることを、ご承知おきngDoCheck

で変化を見てmarkAsPristine()

@Component({ 
    selector: 'my-custom-form-component', 
    templateUrl: './custom-form-component.html', 
    providers: [{ 
    provide: NG_VALUE_ACCESSOR, 
    useExisting: MyCustomFormComponent, 
    multi: true 
    }] 
}) 
export class MyCustomFormComponent implements NG_VALUE_ACCESSOR, OnInit { 

    private control: AbstractControl; 


    ngOnInit() { 
    const self = this; 
    const origFunc = this.control.markAsPristine; 
    this.control.markAsPristine = function() { 
     origFunc.apply(this, arguments); 
     console.log('Marked as pristine!'); 
    } 
    } 

} 

をパフォーマンスは低下しますが、それはあなたがより良い柔軟性を提供します。 stine状態が変更される。上記の解決策では、markAsPristine()が呼び出されたときに通知されます。

@Component({ 
    selector: 'my-custom-form-component', 
    templateUrl: './custom-form-component.html', 
    providers: [{ 
    provide: NG_VALUE_ACCESSOR, 
    useExisting: MyCustomFormComponent, 
    multi: true 
    }] 
}) 
export class MyCustomFormComponent implements NG_VALUE_ACCESSOR, DoCheck { 

    private control: AbstractControl; 

    private pristine = true; 


    ngDoCheck(): void { 
    if (this.pristine !== this.control.pristine) { 
     this.pristine = this.control.pristine; 
     if (this.pristine) { 
     console.log('Marked as pristine!'); 
     } 
    } 
    } 

} 

そして、あなたはあなたのコンポーネントからFormControlインスタンスにアクセスする必要がある場合は、この質問を参照してください:Get access to FormControl from the custom form component in Angularを。

+1

'control'は初期化されていますか? –

関連する問題