【问题标题】:appending the DIV element as a child of the autocomplete container in typeScript将 DIV 元素附加为 typeScript 中自动完成容器的子元素
【发布时间】:2019-02-09 03:20:38
【问题描述】:
我必须将 DIV 元素附加为自动完成容器的子元素,因为我创建了一个包含项目(值)的 c DIV 元素
我用下面给出的代码进行了尝试,但这更像是 javaScript ,所以我不知道在 TypeScript 中实现 DOM 敬请帮助
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
this.parentNode.appendChild(a);
【问题讨论】:
标签:
angular
typescript
typescript-typings
typescript2.0
typescript1.8
【解决方案1】:
使用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);
}
}