Angular2 - Directive - NgControlGroup

回归下进度
NgControlGroup

摘自源码的描述

Creates and binds a control group to a DOM element.
This directive can only be used as a child of {@link NgForm} or {@link NgFormModel}.

 @Directive({
selector: '[ngControlGroup]',
providers: [controlGroupProvider],
inputs: ['name: ngControlGroup'],
exportAs: 'ngForm'
})
export class NgControlGroup extends ControlContainer implements OnInit,
OnDestroy {
/** @internal */
_parent: ControlContainer;

constructor(@Host() @SkipSelf() parent: ControlContainer,
@Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[],
@Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) {
super();
this._parent = parent;
}

ngOnInit(): void { this.formDirective.addControlGroup(this); }

ngOnDestroy(): void { this.formDirective.removeControlGroup(this); }

/**
* Get the {@link ControlGroup} backing this binding.
*/
get control(): ControlGroup { return this.formDirective.getControlGroup(this); }

/**
* Get the path to this control group.
*/
get path(): string[] { return controlPath(this.name, this._parent); }

/**
* Get the {@link Form} to which this group belongs.
*/
get formDirective(): Form { return this._parent.formDirective; }

get validator(): Function { return composeValidators(this._validators); }

get asyncValidator(): Function { return composeAsyncValidators(this._asyncValidators); }
}
  • inputs: 从此指令所在元素上拿ngControlGroup的值为name
  • 在此指令所在的template view中可以ngForm 为变量调用指令内变量

构造:

 
constructor(@Host() @SkipSelf() parent: ControlContainer,
@Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[],
@Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) {
super();
this._parent = parent;
}

在非自身元素的 父元素中找ControlContainer类型的指令 赋值给 parent
在自身元素中找 NG_VALIDATORS 中的各种validator 存放在_validators中类型是any[] -/ Array<Validator|Function> /
async的validator


组件初始化的时候把自己添加到父级上
此处this.formDirective - 是父级,可能是另一个大的group也可能就是form

ngOnInit(): void { this.formDirective.addControlGroup(this); }

组件销毁的时候从父级中去掉此group

ngOnDestroy(): void { this.formDirective.removeControlGroup(this); }

composeValidators/composeAsyncValidators里面其实就是去验证这些validator了,可能会获取到error。具体看
http://dreambo8563.github.io/2016/01/19/Angular2-Directive-validators/

`
get validator(): Function { return composeValidators(this._validators); }

get asyncValidator(): Function { return composeAsyncValidators(this._asyncValidators); }
`