Angular 2 - ng-bootstrap 如何为他们的 NgbRadio 指令提供 NgbRadioGroup 和 NgbButtonLabel?

Angular 2 - How does ng-bootstrap provide the NgbRadioGroup and NgbButtonLabel to their NgbRadio directive?

标签代码如下:

import {Directive} from '@angular/core';

@Directive({
  selector: '[ngbButtonLabel]',
  host:
      {'[class.btn]': 'true', '[class.active]': 'active', '[class.disabled]': 'disabled', '[class.focus]': 'focused'}
})
export class NgbButtonLabel {
  active: boolean;
  disabled: boolean;
  focused: boolean;
}

这里是单选按钮代码:

import {Directive, forwardRef, Input, Renderer2, ElementRef, OnDestroy} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';

import {NgbButtonLabel} from './label';

const NGB_RADIO_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => NgbRadioGroup),
  multi: true
};

let nextId = 0;

/**
 * Easily create Bootstrap-style radio buttons. A value of a selected button is bound to a variable
 * specified via ngModel.
 */
@Directive({
  selector: '[ngbRadioGroup]',
  host: {'data-toggle': 'buttons', 'role': 'group'},
  providers: [NGB_RADIO_VALUE_ACCESSOR]
})
export class NgbRadioGroup implements ControlValueAccessor {
  private _radios: Set<NgbRadio> = new Set<NgbRadio>();
  private _value = null;
  private _disabled: boolean;

  get disabled() { return this._disabled; }
  set disabled(isDisabled: boolean) { this.setDisabledState(isDisabled); }

  /**
   * The name of the group. Unless enclosed inputs specify a name, this name is used as the name of the
   * enclosed inputs. If not specified, a name is generated automatically.
   */
  @Input() name = `ngb-radio-${nextId++}`;

  onChange = (_: any) => {};
  onTouched = () => {};

  onRadioChange(radio: NgbRadio) {
    this.writeValue(radio.value);
    this.onChange(radio.value);
  }

  onRadioValueUpdate() { this._updateRadiosValue(); }

  register(radio: NgbRadio) { this._radios.add(radio); }

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

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

  setDisabledState(isDisabled: boolean): void {
    this._disabled = isDisabled;
    this._updateRadiosDisabled();
  }

  unregister(radio: NgbRadio) { this._radios.delete(radio); }

  writeValue(value) {
    this._value = value;
    this._updateRadiosValue();
  }

  private _updateRadiosValue() { this._radios.forEach((radio) => radio.updateValue(this._value)); }
  private _updateRadiosDisabled() { this._radios.forEach((radio) => radio.updateDisabled()); }
}


/**
 * Marks an input of type "radio" as part of the NgbRadioGroup.
 */
@Directive({
  selector: '[ngbButton][type=radio]',
  host: {
    '[checked]': 'checked',
    '[disabled]': 'disabled',
    '[name]': 'nameAttr',
    '(change)': 'onChange()',
    '(focus)': 'focused = true',
    '(blur)': 'focused = false'
  }
})
export class NgbRadio implements OnDestroy {
  private _checked: boolean;
  private _disabled: boolean;
  private _value: any = null;

  /**
   * The name of the input. All inputs of a group should have the same name. If not specified,
   * the name of the enclosing group is used.
   */
  @Input() name: string;

  /**
   * You can specify model value of a given radio by binding to the value property.
   */
  @Input('value')
  set value(value: any) {
    this._value = value;
    const stringValue = value ? value.toString() : '';
    this._renderer.setProperty(this._element.nativeElement, 'value', stringValue);
    this._group.onRadioValueUpdate();
  }

  /**
   * A flag indicating if a given radio button is disabled.
   */
  @Input('disabled')
  set disabled(isDisabled: boolean) {
    this._disabled = isDisabled !== false;
    this.updateDisabled();
  }

  set focused(isFocused: boolean) {
    if (this._label) {
      this._label.focused = isFocused;
    }
  }

  get checked() { return this._checked; }

  get disabled() { return this._group.disabled || this._disabled; }

  get value() { return this._value; }

  get nameAttr() { return this.name || this._group.name; }

  constructor(
      private _group: NgbRadioGroup, private _label: NgbButtonLabel, private _renderer: Renderer2,
      private _element: ElementRef) {
    this._group.register(this);
  }

  ngOnDestroy() { this._group.unregister(this); }

  onChange() { this._group.onRadioChange(this); }

  updateValue(value) {
    this._checked = this.value === value;
    this._label.active = this._checked;
  }

  updateDisabled() { this._label.disabled = this.disabled; }
}

请注意

@Directive({
  selector: '[ngbButton][type=radio]',
  host: {
    '[checked]': 'checked',
    '[disabled]': 'disabled',
    '[name]': 'nameAttr',
    '(change)': 'onChange()',
    '(focus)': 'focused = true',
    '(blur)': 'focused = false'
  }
})

没有提供者部分,但构造函数有 NgbRadioGroup 和 NgbButtonLabel。此外,在使用指令时,像这样离开 ngbButtonLabel:

<div [(ngModel)]="model" ngbRadioGroup>
  <label>
    <input ngbButton type="radio" name="radio" [value]="values[0]"/> {{ values[0] }}
  </label>
</div>

导致 NgbButtonLabel 没有提供者!错误。我缺少什么声明?这是他们完整存储库的 link:https://github.com/ng-bootstrap/ng-bootstrap

ng-bootstrap 包期望元素

<input ngbButton type="radio" ...>

,您在其上提供了 NgbRadio 指令,将具有您在其上提供 NgbButtonLabel 指令的父元素。

因此您的模板应如下所示:

<label ngbButtonLabel> <======== add ngbButtonLabel attribute
  <input ngbButton type="radio" name="radio" [value]="values[0]"/> {{ values[0] }}
</label>

要理解为什么会这样,您需要从元素的层次结构树中了解 how angular gets dependencies

假设我们的根组件中有以下模板:

app.component.html

<div dirA>
  <comp-b dirB>
    <span dirC>
      <i dirD></i>
    </span>
  </comp-b>
</div>

和以下一组指令:

@Directive({
  selector: '[dirA]',
  providers: [{ provide: 'A', useValue: 'dirA provider' }]
})
export class DirA {}

@Component({
  selector: 'comp-b',
  template: '<ng-content></ng-content>',
  providers: [{ provide: 'B', useValue: 'comp-b provider'}]
})
export class ComponentB {}

@Directive({ selector: 'dirB' })
export class DirB {}

@Directive({ selector: 'dirC' })
export class DirC {}

@Directive({ selector: 'dirD' })
export class DirD {
  constructor(private dirB: DirB) {}
}

注意: private dirB: DirB 就像 private _label: NgbButtonLabel 你的情况

Angular 编译器为我们的模板创建视图工厂:

注意: 我在组件上使用了新的 preserveWhitespaces: false 选项,所以我们在工厂中看不到 textDef

然后 angular creates ViewDefinition 来自这个工厂并且还实例化宿主元素的提供者。

angular 编译器将提供程序带到哪里?

你应该知道的主要事情是 each directive provides its own token:

因此此处的提供者可能如下所示:

<div dirA>               [DirA]
  <comp-b dirB>          [ComponentB, DirB]
    <span dirC>          [DirC] 
      <i dirD></i>       [DirD]
    </span>
  </comp-b>
</div>

以下规则是我们在指令元数据(providers 数组)中声明的提供程序也将添加到宿主元素提供程序中:

<div dirA>               [DirA, { provide: 'A', useValue: 'dirA provider' }]
  <comp-b dirB>          [ComponentB, DirB, { provide: 'B', useValue: 'comp-b provider'}]
    <span dirC>          [DirC] 
      <i dirD></i>       [DirD]
    </span>
  </comp-b>
</div>

现在 angular 正在尝试为 DirB 指令获取提供程序

@Directive({ selector: 'dirD' })
export class DirD {
  constructor(private dirB: DirB) {}
}

Angular依赖解析机制从<i dirD></i>节点开始,一直到<div dirA>:

              null or throw error
                    /\
                 @NgModule
                    /\
                  my-app
<div dirA>          /\     [DirA, { provide: 'A', useValue: 'dirA provider' }]
  <comp-b dirB>     /\     [ComponentB, DirB, { provide: 'B', useValue: 'comp-b provider'}]
    <span dirC>     /\     [DirC]   
      <i dirD></i>  /\     [DirD]  
    </span>
  </comp-b>
</div>

因此 angular 将在 <comp-b dirB> 宿主元素上找到 DirB 提供程序。我们可能认为 angular 将分三步获得 DirB 提供者 但是 实际上 angular uses prototypical inheritance 可以在元素 上定义提供者。

这样我们的树看起来像:

              null or throw error
                    /\
                 @NgModule
                    /\
                  my-app
<div dirA>          /\     [
                             DirA, { provide: 'A', useValue: 'dirA provider' }
                           ]
  <comp-b dirB>     /\     [
                             ComponentB, 
                             DirB, { provide: 'B', useValue: 'comp-b provider'}, 
                             DirA, { provide: 'A', useValue: 'dirA provider' }
                           ]
    <span dirC>     /\     [
                             DirC, ComponentB, 
                             DirB, { provide: 'B', useValue: 'comp-b provider'}, 
                             DirA, { provide: 'A', useValue: 'dirA provider' }
                           ]  
      <i dirD></i>  /\     [
                             DirD, DirC, ComponentB, 
                             DirB, { provide: 'B', useValue: 'comp-b provider'}, 
                             DirA, { provide: 'A', useValue: 'dirA provider' }
                           ]  
    </span>
  </comp-b>
</div>

正如我们实际看到的那样 angular 仅使用一步从 <i dirD></i> 宿主元素中找到 DirB 提供者。