我正在尝试在带有 Angular7 指令的输入字段之后附加一个按钮。问题是 Renderer2 方法 appendChild 将按钮放在输入字段之前。
import { Directive, ElementRef, Input , HostListener, Renderer2, OnInit, OnDestroy } from '@angular/core';
@Directive({
selector: '[appInlineEdit2]'
})
export class InlineEdit2Directive {
@Input() value: any;
private spanElement: Node;
private spanText: Node;
// private children: Node[];
constructor(private el: ElementRef,
public renderer: Renderer2) {
this.spanElement = this.renderer.createElement('span');
// this.spanText = this.renderer.createText('dummy_span');
// this.renderer.appendChild(this.spanElement, this.spanText);
this.renderer.setAttribute(this.spanElement, 'id', 'anchor');
this.renderer.appendChild(this.el.nativeElement, this.spanElement);
// this.renderer.insertBefore(this.el.nativeElement, this.spanElement, null);
this.renderer.listen(this.spanElement, 'click', this.onClick.bind(this));
const button = this.renderer.createElement('button');
this.renderer.setAttribute(button, 'type', 'button');
this.renderer.addClass(button, 'btn');
this.renderer.addClass(button, 'btn-primary');
const buttonText = this.renderer.createText('OK');
this.renderer.appendChild(button, buttonText);
this.renderer.listen(button, 'click', this.onClickOK.bind(this));
this.renderer.appendChild(this.el.nativeElement, button);
// this.renderer.insertBefore(this.el.nativeElement, button, null);
}
ngOnInit() {
console.log(this.el.nativeElement.childNodes);
// this.showMode();
}
}
在模板中:
<div class="input-group col-6" appInlineEdit2 [value]="model">
<input type="text" class="form-control" placeholder="Recipient's username"
[(ngModel)]="model" aria-label="Recipient's username" aria-describedby="basic-addon2">
</div>
我希望按钮位于 DOM 中的输入字段之后。