¿Hay alguna forma angular 2 de omitir el primer desencadenante de ngOnChanges? Actualmente estoy usando este enfoque ingenuo para ignorarlo:
isFirst: boolean = true; ngOnChanges(changes: SimpleChanges) { if (this.isFirst) { this.isFirst = false; return; } console.log(changes); }Puedes usar
https://angular.io/docs/ts/latest/api/core/index/SimpleChange-class.html#!#isFirstChange-anchor
if(changes['prop'].isFirstChange()) { }Para agregar a la respuesta anterior y explicar esto un poco más ...
changes es una matriz de objetos que han sido modificados. Entonces, si tiene una entrada myInput , deberá acceder a ese objeto dentro de la matriz de cambios haciendo changes['myInput'] . myInput contiene:
previousValue - valor anterior del objeto (antes del cambio)currentValue - valor actual del objeto que ha sido cambiadofirstChange : booleano sobre si esta es la primera vez que ha habido un cambio (tenga en cuenta que esto será verdadero cuando el componente se inicialice y falso de lo contrario) - isFirstChange() devolverá verdadero si este es el primer cambio.Código:
//your input @Input() myInput: any; ngOnChanges(changes: any) { //check if this isn't the first change of myInput if(!changes['myInput'].isFirstChange()) { //do something } }Si tiene muchas entradas, pero no puede saber con certeza cuál de ellas está configurada, puede usar
isFirstChange establecido ngOnChanges(changes: SimpleChanges) { const isFirstChange = Object.values(changes).some(c => c.isFirstChange()); } Cuidado: si no se configura @Input , isFirstChange será false porque Array.some se detiene en el primer valor true .