Skip to content

BUG: ViewChild property is set before OnInit #21800

@kukjevov

Description

@kukjevov

I'm submitting a...


[X] Regression (a behavior that used to work and stopped working in a new release)
[X] Bug report  
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior

Currently when you have

@Component(
{
    selector: 'home-view',
    templateUrl: 'home.component.html'
})
export class HomeComponent implements OnInit, AfterViewInit
{
    @ViewChild('treeview')
    public tree: FancyTreeComponent;

    public ngOnInit()
    {
        console.log(this.tree);//NOT NULL, SHOULD BE NULL
    }

    public ngAfterViewInit()
    {
        console.log(this.tree);//NOT NULL, OK
    }
}

before i dont know in which version was this.tree null before first call of ngAfterViewInit, now its not, which allows me to access FancyTreeComponent before it was properly initialized!

Before i was able to check for null and knew that component was not initialized.

Even documentation says View queries are set before the ngAfterViewInit callback is called. which does not deny that it can be initialized before ngOnInit but in past it was exactly like that it was null.

Is it a not mentioned breaking change?

Expected behavior

ViewChild, ViewChildren, ContentChild, ContentChildren should be initialized/set only after ngAfterViewInit, respectively ngAfterContentInit which are not.

Minimal reproduction of the problem with instructions

Use code above.

What is the motivation / use case for changing the behavior?

Environment


Angular version: 5.1.2


Browser: All
- [ ] Chrome (desktop) version XX
- [ ] Chrome (Android) version XX
- [ ] Chrome (iOS) version XX
- [ ] Firefox version XX
- [ ] Safari (desktop) version XX
- [ ] Safari (iOS) version XX
- [ ] IE version XX
- [ ] Edge version XX
 
For Tooling issues:
- Node version: 9.4.0  
- Platform:  Windows 

Others:

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions