従来のラベル/スパン スタイルやその他の機能にスタイルを追加するカスタム チェックボックス ディレクティブがあります。ラッパーを自分自身の周りに挿入し、スパンを横に挿入します。構造ディレクティブに配置すると、DOM の操作に失敗することに気付きました。セットアップのほとんどはコンストラクターで行われますが、構造上の親とうまく連携するには、Angular のライフサイクルを意識したものにする必要があるのではないかと考えています。
問題の DOM の例:
<ng-container *ngIf="test">
<!-- <div class="row align-middle"> -->
<input type="text" alloy placeholder="you should see a checkbox">
<input type="checkbox" alloy alloyLabel="default">
<!-- </div> -->
</ng-container>
そのコメントされたdivで動作します。ただし、直接の親である ng-container を使用すると、レンダラーは DOM の挿入に失敗します。これはコンストラクタです:
constructor(
protected el: ElementRef,
protected renderer: Renderer2,
protected focusMonitor: FocusMonitor,
@Host() @Optional() protected identityDirective: AlloyIdentityDirective) {
super();
// If we don't have a label wrapper, create one
this.labelElement = this.renderer.parentNode(el.nativeElement);
if (!(this.labelElement instanceof HTMLLabelElement)) {
const label = this.renderer.createElement('label');
// Inject wrapper then move native element (input) within it.
this.renderer.insertBefore(this.labelElement, label, this.el.nativeElement);
this.renderer.removeChild(this.labelElement, this.el.nativeElement);
this.renderer.appendChild(label, this.el.nativeElement);
this.labelElement = label;
// We must add the span because that's what actually gets the check styling
this.styledElement = this.renderer.createElement('span');
this.renderer.appendChild(this.labelElement, this.styledElement);
}
編集:結果DOMを追加
実際のエラーはありません。欠陥のあるケース ( の直接の親ng-container
) では、最初の要素になりますが、インジェクションはありません:
<input type="checkbox" alloy alloyLabel="default">
ラッパーdiv
を使用すると、予想されるインジェクションが得られます (_ngcontent* が削除されます):
<label class="alloy-check-wrapper">
<input alloy="" alloylabel="default" type="checkbox" class="alloy-check">
<span></span>
<span class="alloyLabel">default</span>
</label>