2017-06-24 26 views
15

從自定義表單組件訪問FormControl我在我的角度應用,它實現ControlValueAccessor界面自定義表單控制組件。獲取角

不過,我想訪問FormControl情況下,用我的組件相關聯。我正在使用具有FormBuilder的反應形式,並使用formControlName屬性提供表單控件。

那麼,如何從我的自定義表單組件內部訪問FormControl實例?

回答

14

這種溶液從the discussion在角倉庫誕生。如果您對這個問題感興趣,請務必閱讀或者更好地參與。


我研究FormControlName指令代碼和它激發了我想寫以下解決方案:

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

    @Input() formControlName: string; 

    private control: AbstractControl; 


    constructor (
    @Optional() @Host() @SkipSelf() 
    private controlContainer: ControlContainer 
) { 
    } 


    ngOnInit() { 

    if (this.controlContainer) { 
     if (this.formControlName) { 
     this.control = this.controlContainer.control.get(this.formControlName); 
     } else { 
     console.warn('Missing FormControlName directive from host element of the component'); 
     } 
    } else { 
     console.warn('Can\'t find parent FormGroup directive'); 
    } 

    } 

} 

我注入母公司FormGroup到組件,然後讓從具體FormControl它使用通過formControlName綁定獲得的控件名稱。

然而,被告知,即這種解決方案對於其中FormControlName指令主機元件上使用的情況下,使用專門定製。它在其他情況下不起作用。爲此,您需要添加一些額外的邏輯。如果您認爲這應該由Angular解決,請務必訪問the discussion

+0

從你有'this.control'在哪裏? – DAG

+0

@DAG我在回答說:'我注入父FormGroup到該組件,然後使用通過formControlName獲得的控制名從它得到特定FormControl binding.' –

+2

@SlavaFominII:代替注射母體形式組,然後使用formControllerName輸入綁定訪問控件,我們不能僅僅通過表單控件作爲輸入綁定?我有一個類似的要求,我想從自定義表單組件訪問表單控件,並將該表單控件作爲輸入綁定到自定義表單組件。 – Ritesh

2

正如@Ritesh已經寫在註釋中,你可以通過表單控件作爲輸入綁定:

<my-custom-form-component [control]="myForm.get('myField')" formControlName="myField"> 
</my-custom-form-component> 

然後你就可以得到您的自定義窗體組件內部表單控件實例是這樣的:

@Input() control: FormControl;