2017-04-21 50 views
2

我有一個實現ControlValueAccessor的自定義窗體組件。該組件具有觸摸的內部屬性。Angular 2自定義窗體組件:提供標記方法

export class BmInputComponent implements ControlValueAccessor, Validator { 

    private onTouchedCallback:() => {}; 
    private touched: boolean = false; 

    registerOnTouched(fn: any) { 
     this.onTouchedCallback = fn; 
    } 

    onBlur() { 
     this.touched = true; 
     this.onTouchedCallback(); 
    } 
} 

我需要實現像

markTouched() { 
    this.touched = true; 
} 

這可能由該組件的用戶時markAsTouched在formControl執行被調用的方法:customInputControl.markAsTouched()

我無法找到一個angular-這樣做的方法。

@Edit: 試圖注入NgControl:

@Component({ 
    selector: 'bm-input', 
    templateUrl: './bm-input.component.html', 
    encapsulation: ViewEncapsulation.None, 
    providers: [ 
     { 
      provide: NG_VALUE_ACCESSOR, 
      useExisting: forwardRef(() => BmInputComponent), 
      multi: true 
     } 
    ] 
}) 
export class BmInputComponent implements ControlValueAccessor, Validator { 

    private onTouchedCallback:() => {}; 
    private touched: boolean = false; 

    constructor(@Self() @Optional() public _formControl: NgControl) { 
     this._viewDate = new Date(); 
     if (this._formControl) { 
      this._formControl.valueAccessor = this; 
      this._formControl.statusChanges.subscribe(this.markTouched); 
     } 
    } 
    registerOnTouched(fn: any) { 
     this.onTouchedCallback = fn; 
    } 

    onBlur() { 
     this.touched = true; 
     this.onTouchedCallback(); 
    } 

    markTouched() { 
     if(this._formControl.touched) 
      this.touched = true; 
    } 

} 

但我正在逐漸Cannot instantiate cyclic dependency! NgControl當組件與formControl調用。

回答

1

您是否試過@SkipSelf()而不是@Self()?

+0

不引發異常,但它沒有收到注入的控件 – Zucca