【问题标题】:Angular DOM Manipulation: Why ViewChildren works and ViewChild doesn'tAngular DOM 操作:为什么 ViewChildren 有效而 ViewChild 无效
【发布时间】:2019-06-20 05:11:58
【问题描述】:

我发现 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(这样他就可以将孩子的数量记录到控制台)。

我将其简化为只使用@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
    );
  }
}

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

ERROR TypeError: 无法在“Node”上执行“removeChild”:参数 1 不是“Node”类型。

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

【问题讨论】:

    标签: angular dom components viewchild


    【解决方案1】:

    我相信这应该可行:

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

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 2020-03-09
      • 2011-07-05
      • 2012-01-15
      • 2013-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多