ng-onpush
TypeScript icon, indicating that this package has built-in type declarations

1.0.0-beta.1 • Public • Published

NgOnpush

test: passed tests with angular: 14.1.2 license:

Usage

Set the OnPush strategy to the root component.

@Component({
    selector: "app-root",
    template: `...`,
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {}

Now, if some property is updated on a request or on a timer, just decorate it.

@Component({
    selector: "my-component",
    template: "{{ value }}",
})
export class WatchChangesComponent implements AfterViewInit {
    @WatchChanges()
    value = "";

    ngAfterViewInit(): void {
        setTimeout(() => {
            this.value = "message";
        });
    }
}

It's the same as

@Component({
    selector: "my-component",
    template: "{{ value }}",
})
export class MyComponent implements AfterViewInit {
    value = "";

    constructor(private changeDetectorRef: ChangeDetectorRef) {}

    ngAfterViewInit(): void {
        setTimeout(() => {
            this.value = "message";
            this.changeDetectorRef.markForCheck();
        });
    }
}

Use the UpdateImmediately decorator to detect changes.

@Component({
    selector: "my-component",
    template: "{{ text }}",
})
export class MyComponent implements AfterViewInit {
    @UpdateImmediately()
    text = "initial";

    constructor(private hostRef: ElementRef<HTMLElement>) {}

    ngAfterViewInit(): void {
        setTimeout(() => {
            const message = "foo";

            this.text = message;

            this.hostRef.nativeElement.textContent === message; // true
        });
    }
}

It's the same as

@Component({
    selector: "my-component",
    template: "{{ text }}",
})
export class MyComponent implements AfterViewInit {
    @UpdateImmediately()
    text = "initial";

    constructor(
        private changeDetectorRef: ChangeDetectorRef,
        private hostRef: ElementRef<HTMLElement>,
    ) {}

    ngAfterViewInit(): void {
        setTimeout(() => {
            const message = "foo";

            this.text = message;
            this.changeDetectorRef.detectChanges();

            this.hostRef.nativeElement.textContent === message; // true
        });
    }
}

Package Sidebar

Install

npm i ng-onpush

Weekly Downloads

124

Version

1.0.0-beta.1

License

MIT

Unpacked Size

33.8 kB

Total Files

19

Last publish

Collaborators

  • paveldymkov