Angular2: rendering / reloading a component's template

前端 未结 3 2055
无人共我
无人共我 2021-01-03 02:13

Ideally I would need to reload / rerender my component\'s template but if there is a better way to do this I will gladly implement it.

Desired behavior:

3条回答
  •  死守一世寂寞
    2021-01-03 02:41

    Angular has two change detection strategies:

    • The default strategy, that automatically detects changes in the model and re-render the components accordingly.

    • OnPush, that only re-renders the component when you explicitly tell it to do so. See also https://angular.io/docs/ts/latest/api/core/index/ChangeDetectionStrategy-enum.html

    The OnPush strategy can have a better performance when you have several elements on a page or when you want to have more control over the rendering process.

    In order to use this strategy, you have to declare it in your component:

    @Component({
        selector: '[ibos-navigation-element]',
        template: `...`,
        changeDetection: ChangeDetectionStrategy.OnPush
    })
    

    And inject in your constructor:

    constructor(
        private changeDetector: ChangeDetectorRef,
    ) {}
    

    When you want to fire the change detection so the component can be re-rendered (in your case, right after a new IBO/client is added to the model), call:

    this.changeDetector.markForCheck();
    

    Check the live demo from the official tutorial: http://plnkr.co/edit/GC512b?p=preview

    If the problem is not about change detection, but related to CSS/SCSS styling, bear in mind that in Angular 2 each component has its own set of CSS classes and they're not "inherited" by the "children" elements. They're completely isolated from each another. One solution could be the creation of global CSS/SCSS styles.

提交回复
热议问题