代码之家  ›  专栏  ›  技术社区  ›  ssuperczynski Pravesh Jain

初始化子级后,子DOM上父组件的操作将导致表达式ChangedAfterithasbeencheckedError

  •  0
  • ssuperczynski Pravesh Jain  · 技术社区  · 6 年前

    在初始化子组件之后,我想从父组件对子组件进行一些操作。

    起源:

    export class ParentComponent implements AfterViewInit {
      @ViewChild('child') childComponent: ChildComponent;
    
      ngAfterViewInit() {
        this.childComponent.domMethod('boo');
      }
    }
    
    <p>parent</p>
    
    <app-child #child></app-child>
    

    孩子:

    export class ChildComponent implements OnInit {
      constructor(private readonly cdr: ChangeDetectorRef,) {
    
      }
      public term = '';
      public items;
      ngOnInit() {
        this.items = [
          { name: 'foo' },
          { name: 'bar' },
          { name: 'baz' },
          { name: 'boo' },
          { name: 'zoo' },
        ];
      }
    
      domMethod(value: string) {
        // const input = document.getElementById('childInput') as HTMLInputElement;
        // input.value = value;
        this.term = value;
        this.cdr.markForCheck(); // <-- enabling this line cause ExpressionChangedAfterItHasBeenCheckedError
      }
    }
    
    <p>child</p>
    
    <input type="text" id="childInput" [(ngModel)]="term">
    
    <ul>
        <li *ngFor="let item of items | search: term">{{item.name}}</li>
    </ul>
    

    链接到 StackBlitz 用于复制

    编辑:

    如果我添加 setTimeout 对于父组件,它可以工作。没有它我能做到吗 设置超时 ?

      ngAfterViewInit() {
        setTimeout(() => {
          this.childComponent.domMethod('boo');
        })
      }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Abhishek    6 年前

    你已经用过了 detectionChanges 为此:

    constructor(private _cd: ChangeDetectorRef){}
    
    ngAfterViewInit() {
          this.childComponent.domMethod('boo');
          this._cd.detectChanges();
    
      }