Angular DOM 操作:为什么 ViewChildren 有效而 ViewChild 无效

Angular DOM Manipulation: Why ViewChildren works and ViewChild doesn't

我发现了一篇由 ngWizard 撰写的有趣文章 here,其中引用了一个关于删除组件的正确方法的 stackblitz 示例。

@Component({
  selector: 'app-root',
  template: `
    <button (click)="remove()">Remove child component</button>
    <a-comp #c></a-comp>
  `
})
export class AppComponent implements AfterViewChecked {
  @ViewChildren('c', {read: ElementRef}) childComps: QueryList<ElementRef>;


  constructor(private hostElement: ElementRef, private renderer: Renderer2) {
  }

  ngAfterViewChecked() {
    console.log('number of child components: ' + this.childComps.length);
  }

  remove() {
    this.renderer.removeChild(
      this.hostElement.nativeElement,
      this.childComps.first.nativeElement
    );
  }
}

在这个例子中,他使用了@ViewChildren(这样他就可以将 children 的数量记录到控制台)。

我将其简化为仅使用 @ViewChild,如下所示 (stackblitz):

export class AppComponent {
  @ViewChild('c') child:ElementRef;


  constructor(private hostElement: ElementRef, private renderer: Renderer2) {
  }

  remove() {
    this.renderer.removeChild(
      this.hostElement.nativeElement,
      this.child.nativeElement
    );
  }
}

不幸的是,这是我得到的结果:

错误类型错误:无法在 'Node' 上执行 'removeChild':参数 1 不是 'Node' 类型。

为什么引用 ViewChildren 中的第一个 elementRef 有效而引用 ViewChild 中的单个 elementRef 无效?

我相信这应该有效:

   @ViewChild('c', {read: ElementRef}) child:ElementRef;

希望对您有所帮助。