2017-08-06 47 views
2

我創建了代表密碼窗體控件的自定義組件(下面的代碼被簡化了)。訪問自定義窗體控件的有效值

PasswordComponent(HTML)

<form [formGroup]="passwordForm"> 
    ... 
    <input formControlName="password" type="password"> 
</form> 

PasswordComponent(TS)

... 
@Component({ 
    selector: 'password', 
    templateUrl: './password.component.html', 
    styleUrls: ['./password.component.css'], 
    providers: [{ 
    provide: NG_VALUE_ACCESSOR, 
    useExisting: forwardRef(() => PasswordComponent), 
    multi: true 
    }] 
}) 
export class PasswordComponent implements ControlValueAccessor { 

    passwordForm: FormGroup; 
    onChange = (password: string) => { }; 
    onTouched =() => { };     

    constructor() { 
    this.passwordForm = new FormGroup({ 
     ... 
     password: new FormControl('') 
    }); 

    this.passwordForm.valueChanges.subscribe(data => this.onChange(this.value)); 
    } 

    get value(): string { 
    return this.passwordForm.get('password').value; 
    } 

    writeValue(password: string): void { 
    this.passwordForm.get('password').setValue(password); 
    this.onChange(this.value); 
    } 

    registerOnChange(fn: any): void { this.onChange = fn; } 

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

    setDisabledState?(isDisabled: boolean): void { } 
} 

我使用的其他成分,而不是標準的輸入元件:

<form [formGroup]="userForm"> 
    ... 
    <password formControlName="password"></password> 
</form> 

驗證器從外來形式(它們沒有在PasswordComponent中定義)

this.userForm = fb.group({ 
    ... 
    password: ['', [Validators.minLength(10), Validators.maxLength(100)]] 
}); 

我的問題是:如何從PasswordComponent中獲得<password>元素有效性?我想根據有效性對其進行風格化。換句話說,我怎樣才能從代表這個控件的PasswordComponent獲得userForm的'密碼'控件的有效性。

回答

3

由於我們無法直接從DI系統獲取NgControl實例,因爲我們將得到循環依賴錯誤。下圖顯示了爲什麼我們在我們的自定義值存取注入NgControl它發生:

enter image description here

現在應該清楚的是,我們有NgControl -> FormControlName -> ValueAccessor -> CustomValueAccessor -> NgControl循環依賴

要解決它,你可以利用Injector到實現這一目標:

component.ts

import { NgControl } from '@angular/forms'; 
export class PasswordComponent implements ControlValueAccessor { 
    ... 
    ngControl: NgControl; 

    constructor(private inj: Injector) { 
    ... 
    } 

    ngOnInit() { 
    this.ngControl = this.inj.get(NgControl) 
    } 

template.html

{{ ngControl.control.valid }} 

Plunker Example

+0

這個工程就像一個魅力,但它看起來這麼難看,或者這只是我是誰認爲這?它看起來像一個非常基本的用例 – dendimiiii

+0

你能否更詳細地解釋一下這裏發生了什麼?爲什麼我們會有一個循環dep錯誤?爲什麼注射器沒有一個? – Ced

+0

@Ced謝謝,更新 – yurzui