简体   繁体   中英

Is there an Angular2 view updated lifecycle hook?

I have a child component, receiving data from its parent and displaying text in a div. It is possible the parent sends undefined as data. When it does the div is supposed to transition its height to 0, which I do via css transition. As I don't know the length of the text, the div's height is supposed to be transitioned to auto . I found a code sample doing so, which I've transformed to fit into my component.

export class LanguageDetail implements OnChange, OnInit {
    @Input() language: Language
    @ViewChild("detailPanel") detailPanel: ElementRef;

    private shownLanguage: Language;

    ngOnInit() {
        this.shownLanguage = new Language();
    }

    ngOnChange() {
        if (this.detailPanel) {
            var detailPanel: JQuery = $(this.detailPanel.nativeElement);

            if (this.language) {
                ...
                // calculate the end height and apply a transition with fixed values to this.shownLanguage
                this.shownLanguage = this.language;

                oldHeight = detailPanel.height();
                detailPanel.height("auto");
                newHeight = detailPanel.height();
                detailPanel.height(oldHeight);
                ...
            } else {
                ...
                // do a transition to 0 for this.shownLanguage
                ...
            }
        }
    }
}

Now the problem is, when ngOnChange gets called, the property language has actually changed, the view however is bound to this.shownLanguage and does not actually update when this.language is assigned to it within the ngOnChange function. Same goes for a binding to this.language itself. The OnChange event gets hit too early. With the text missing in the div, I do not receive the correct height of it and so my calculation runs incorrect. Is there actually an event that is triggered when the view changes or is there a way to force redrawing of the view so I can actually get the div with the correct height?

Sure, what about AfterViewChecked

  [LifecycleHooks.OnInit, OnInit],
  [LifecycleHooks.OnDestroy, OnDestroy],
  [LifecycleHooks.DoCheck, DoCheck],
  [LifecycleHooks.OnChanges, OnChanges],
  [LifecycleHooks.AfterContentInit, AfterContentInit],
  [LifecycleHooks.AfterContentChecked, AfterContentChecked],
  [LifecycleHooks.AfterViewInit, AfterViewInit],
  [LifecycleHooks.AfterViewChecked, AfterViewChecked],

AfterViewChecked - Implement this interface to get notified after every check of your component's view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM