Angular版本:6.1
我正在尝试使用Kara Erickson所谓的Composite ControlValueAccessor来实现自定义控件,如演示文稿Angular Forms – Kara Erickson – AngularConnect 2017所示。控件的值应设置为两个子输入值之一。
问题是writeValue()
似乎仅在最初被调用,而不是在进一步的值更改时被调用。
这里是stackblitz demo。
<form #f="ngForm" (ngSubmit)="f.form.valid && Submit(f)">
<confirm-password name='password' ngModel #pwd='ngModel'></confirm-password>
<div>{{pwd.status}}</div>
</form>
<div [formGroup]='pass'>
<label>Password:
<input type="password" formControlName='pwd1' (blur)='onTouched()'>
</label>
<div *ngIf="controlDir.touched && controlDir.control.errors?.required"
class="error">Password is required.</div>
<label>Please re-enter password:
<input type="password" formControlName='pwd2' (blur)='onTouched()'>
</label>
<div class='error' *ngIf='controlDir.touched && controlDir.control.errors?.notEqual &&
!controlDir.errors?.required'>Passwords do not match.</div>
</div>
import { Component, Self, OnInit, OnDestroy } from '@angular/core';
import { ControlValueAccessor, AbstractControl, NgControl,
ValidatorFn, Validators, FormGroup, FormControl } from '@angular/forms';
import { Subscription } from 'rxjs';
@Component({
selector: 'confirm-password',
templateUrl: './confirm-password.component.html',
styleUrls: ['./confirm-password.component.css']
})
export class ConfirmPasswordComponent implements ControlValueAccessor, OnInit, OnDestroy
{
password: string; // the value of the control should be set to this value
pass = new FormGroup({
pwd1: new FormControl(),
pwd2: new FormControl()
});
private onChange: (value: string) => void;
private onTouched: (value: string) => void;
private valueChanges: Subscription;
constructor(@Self() public controlDir: NgControl)
{
controlDir.valueAccessor = this;
}
ngOnInit()
{
const control = this.controlDir.control;
let myValidators = [
Validators.required,
equalValidator(this.pass.controls.pwd1,
this.pass.controls.pwd2)
]
// ovoid overwriting any existing validators
let validators = control.validator
? [control.validator, ...myValidators]
: [...myValidators];
control.setValidators(validators);
control.updateValueAndValidity();
}
writeValue(val: any)
{
/* whether everything inside of this method is commented out or not
doesn't seem to affect anything */
console.log(val);
//val && this.pass.setValue(val, {emitEvent: false});
this.password = val;
}
registerOnChange(fn: (val: any) => void)
{
this.valueChanges = this.pass.valueChanges.subscribe(fn);
}
registerOnTouched(fn: () => void)
{
this.onTouched = fn;
}
setDisabledState(disabled: boolean)
{
disabled ? this.pass.disable() : this.pass.enable();
}
ngOnDestroy()
{
this.valueChanges.unsubscribe();
}
}
export function equalValidator(el1, el2): ValidatorFn
{
return (ctrl: AbstractControl): {[key: string]: any} | null => {
const notEqual = el1.value !== el2.value;
return notEqual ? {"notEqual": true} : null;
};
}
答案 0 :(得分:4)
writeValue
的目的是通知组件有关外部的更改/父组件的表单控件。通常,您要做的就是将外部的更改绑定到本地变量。
要向外界通报组件内部的变化,您需要调用onChange
方法。您可以像通常调用事件发射器那样来调用它。
我在这里整理了几个示例:https://www.tsmean.com/articles/angular/angular-control-value-accessor-example/
答案 1 :(得分:3)
writeValue
是在您通过用户输入而不是通过用户更改控制值(例如,通过设置ngModel属性或控制值)来调用的。
https://stackblitz.com/edit/angular-hu2bfs?file=src/app/app.module.ts
我已删除了由于滥用ngModel
而引起的错误
如您所见,如果您直接输入额外的输入新值并按下按钮,则会调用writeValue
。
将其包装起来-控制器更改模型值时调用writeValue
,而writeValue的目的是做必要的工作以通过自定义控件反映模型更改。