防止 ngOnChanges 在发出事件后触发(Angular 2+)

Fra*_*ica 5 javascript typescript angular

在 Angular 2+ 中,可以通过使用@Input@Output参数来实现自定义双向数据绑定。所以如果我想让子组件与第三方插件通信,我可以这样做:

export class TestComponent implements OnInit, OnChanges {
    @Input() value: number;
    @Output() valueChange = new EventEmitter<number>();

    ngOnInit() {
        // Create an event handler which updates the parent component with the new value
        // from the third party plugin.

        thirdPartyPlugin.onSomeEvent(newValue => {
            this.valueChange.emit(newValue);
        });
    }

    ngOnChanges() {
        // Update the third party plugin with the new value from the parent component

        thirdPartyPlugin.setValue(this.value);
    }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

<test-component [(value)]="value"></test-component>
Run Code Online (Sandbox Code Playgroud)

在第三方插件触发事件通知我们发生变化后,子组件通过调用this.valueChange.emit(newValue). 问题是,ngOnChanges然后在子组件中触发,因为父组件的值已更改,从而导致thirdPartyPlugin.setValue(this.value)被调用。但是插件已经处于正确的状态,所以这是一个潜在的不必要/昂贵的重新渲染。

所以我经常做的是在我的子组件中创建一个标志属性:

export class TestComponent implements OnInit, OnChanges {
    ignoreModelChange = false;

    ngOnInit() {
        // Create an event handler which updates the parent component with the new value
        // from the third party plugin.

        thirdPartyPlugin.onSomeEvent(newValue => {
            // Set ignoreModelChange to true if ngChanges will fire, so that we avoid an
            // unnecessary (and potentially expensive) re-render.

            if (this.value === newValue) {
                return;
            }

            ignoreModelChange = true;

            this.valueChange.emit(newValue);
        });
    }

    ngOnChanges() {
        if (ignoreModelChange) {
            ignoreModelChange = false;

            return;
        }

        thirdPartyPlugin.setValue(this.value);
    }
}
Run Code Online (Sandbox Code Playgroud)

但这感觉就像一个黑客。

在 Angular 1 中,使用=绑定接收参数的指令具有完全相同的问题。因此,相反,我将通过 requires 来完成自定义的双向数据绑定ngModelController,这不会在模型更新后导致重新渲染:

// Update the parent model with the new value from the third party plugin. After the model
// is updated, $render will not fire, so we don't have to worry about a re-render.

thirdPartyPlugin.onSomeEvent(function (newValue) {
    scope.$apply(function () {
        ngModelCtrl.$setViewValue(newValue);
    });
});

// Update the third party plugin with the new value from the parent model. This will only
// fire if the parent scope changed the model (not when we call $setViewValue).

ngModelCtrl.$render = function () {
    thirdPartyPlugin.setValue(ngModelCtrl.$viewValue);
};
Run Code Online (Sandbox Code Playgroud)

这有效,但ngModelController似乎真的是为表单元素设计的(它内置了验证等)。所以在不是表单元素的自定义指令中使用它感觉有点奇怪。

问题:Angular 2+ 中是否有在子组件中实现自定义双向数据绑定的最佳实践,在ngOnChanges使用 更新父组件后不会在子组件中触发EventEmitter?或者我应该ngModel像在 Angular 1 中那样集成,即使我的子组件不是表单元素?

提前致谢!


更新:我在评论中查看了@Maximus 建议的有关 Angular 中更改检测的所有信息。看起来detach方法 onChangeDetectorRef将阻止更新模板中的任何绑定,如果这是您的情况,这可能有助于提高性能。但它并不能阻止ngOnChanges被调用:

thirdPartyPlugin.onSomeEvent(newValue => {
    // ngOnChanges will still fire after calling emit

    this.changeDetectorRef.detach();
    this.valueChange.emit(newValue);
});
Run Code Online (Sandbox Code Playgroud)

到目前为止,我还没有找到一种使用 Angular 的变化检测来实现这一点的方法(但我在这个过程中学到了很多东西!)。

我最终用ngModel和尝试了这个ControlValueAccessor。这似乎完成了我所需要的,因为它的行为与ngModelControllerAngular 1 中的一样:

export class TestComponentUsingNgModel implements ControlValueAccessor, OnInit {
    value: number;

    // Angular will pass us this function to invoke when we change the model

    onChange = (fn: any) => { };

    ngOnInit() {
        thirdPartyPlugin.onSomeEvent(newValue => {
            this.value = newValue;

            // Tell Angular to update the parent component with the new value from the third
            // party plugin

            this.onChange(newValue);
        });
    }

    // Update the third party plugin with the new value from the parent component. This
    // will only fire if the parent component changed the model (not when we call
    // this.onChange).

    writeValue(newValue: number) {
        this.value = newValue;

        thirdPartyPlugin.setValue(this.value);
    }

    registerOnChange(fn: any) {
        this.onChange = fn;
    }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

<test-component-using-ng-model [(ngModel)]="value"></test-component-using-ng-model>
Run Code Online (Sandbox Code Playgroud)

但同样,如果自定义组件不是表单元素,使用ngModel似乎有点奇怪。

cra*_*s84 5

也遇到了这个问题(或者至少是非常相似的问题)。

我最终使用了你上面讨论的 hacky 方法,但做了一个小的修改,我使用了 setTimeout 来重置状态以防万一。

(对我个人而言,如果使用双向绑定,ngOnChanges 主要是有问题的,因此如果不使用双向绑定,则 setTimeout 会阻止挂起的 disableOnChanges)。

changePage(newPage: number) {
    this.page = newPage;
    updateOtherUiVars();

    this.disableOnChanges = true;
    this.pageChange.emit(this.page);
    setTimeout(() => this.disableOnChanges = false, 0);     
}

ngOnChanges(changes: any) {
    if (this.disableOnChanges) {
        this.disableOnChanges = false;
        return;
    }

    updateOtherUiVars();
}
Run Code Online (Sandbox Code Playgroud)


JSF*_*JSF 0

这正是 Angular 的意图,您应该尝试与之合作而不是反对更改检测的工作原理是组件检测其模板绑定中的更改并将其沿着组件树传播。如果您可以以依赖组件输入的不变性的方式设计应用程序,则可以通过设置来手动控制它,@Component({changeDetection:ChangeDetectionStrategy.OnPush})该设置将测试引用以确定是否继续对子组件进行更改检测。

所以,话虽如此,我的经验是,第三方插件的包装器可能无法有效地处理和适当地利用这种类型的策略。您应该尝试使用上述知识以及良好的设计选择,例如分离表示与容器组件的关注点,以利用检测策略来实现良好的性能。

您还可以传递changes: SimpleChangesngOnInit(changes: SimpleChanges)检查该对象以了解有关数据流的更多信息。