parent.appendChild 不是函数

cup*_*_of 4 angular

我想用renderer2的追加子功能,但我有一些困难,移动整个组件。这是我的组件的缩短版本。

ts:

@ViewChild('test', { static: false }) test;
@ViewChild('test2', { static: false }) test2;

this.renderer.appendChild(this.test, this.test2);
Run Code Online (Sandbox Code Playgroud)

html:

<div #test></div>

<my-component #test2></my-component>
Run Code Online (Sandbox Code Playgroud)

所以基本上我只想</my-component>使用该appendChild函数移动到它上面的 div 中。但是当我执行它时,我收到错误:

parent.appendChild is not a function

任何想法为什么会出错?

yur*_*zui 9

您应该将 DOM 元素传递给此方法:

@ViewChild('test', { static: false }) test: ElementRef;
@ViewChild('test2', { static: false, read: ElementRef }) test2: ElementRef;
...

this.renderer.appendChild(this.test.nativeElement, this.test2.nativeElement);
Run Code Online (Sandbox Code Playgroud)