我必须将DIV元素作为自动完成容器的子元素附加,因为我创建了一个包含项目(值)的c DIV元素
我尝试使用下面给出的代码,但这更像是javaScript,所以我不知道实现DOM IN TypeScript对此有何帮助
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
this.parentNode.appendChild(a);
使用Renderer2
:stackblitz
@Component({
selector: 'hello',
template: `<div #container></div>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@ViewChild('container') container: ElementRef<HTMLDivElement>;
constructor(
private R: Renderer2
) {}
ngOnInit() {
this.appendElement();
}
appendElement() {
const el = this.R.createElement('a');
this.R.setAttribute(el, 'id', 'autocomplete-list');
this.R.setAttribute(el, 'class', 'autocomplete-items');
const txt = this.R.createText('This is a link');
this.R.appendChild(el, txt);
this.R.appendChild(this.container.nativeElement, el);
}
}