代码之家  ›  专栏  ›  技术社区  ›  Dolf Andringa

在角度组件的DOM更改后运行函数,类似于ngAfterViewInit

  •  1
  • Dolf Andringa  · 技术社区  · 6 年前

    我有一个基于输入实例化一堆指令的组件。在下面的示例中(不是真正的代码,但我尽可能地简化以说明问题),组件以 Input() MyService 把它变成 this.fields ,和 dynamicField 在指令呈现完所有字段之后,我想 doSomething() . 我使用 ngAfterViewInit()

    现在的问题是:稍后,我想触发 这个。菲尔德 一些组件被移除,而另一些组件则从组件中添加。但是,在所有指令再次呈现之后,如何再次运行doSomething()? ngAfterViewinit()

    import { MyService } from './myService.service';
    
    @Component({
        selector: 'mycomp',
        template: '<ng-template *ngFor="let field of fields;" dynamicField [config]="field"></ngtemplate><button (click)="myTrigger()">Trigger</button>'
    })
    export class MyComponent implements AfterViewInit, OnInit{
    
        @Input() config: object;
        fields: object[];
    
        constructor(myService: MyService){
        }
    
        ngOnInit(){
            this.fields = this.myService.getFields(this.config);
        }
    
        myTrigger(){
            this.fields.pop();
            this.fields.push({'id': 'someotherfield', 'label':'someotherfield'})
        }
    
        doSomething() {
            console.log('dosomething');
        }
    
        ngAfterViewInit(){
            doSomething();
        }
    
    
    }
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   PuntanetDeveloper    6 年前

    试试这个:

    import { Component, AfterViewChecked, OnInit} from '@angular/core';
    
    
    export class MyComponent implements AfterViewChecked, OnInit{
    
    
         ngAfterViewChecked(){
             doSomething();
         }
    
    }
    
        2
  •  2
  •   danday74    6 年前

    myTrigger(){
      this.fields.pop();
      this.fields.push({'id': 'someotherfield', 'label':'someotherfield'})
      setTimeout(() => {
        this.doSomething()
      })
    }