2017-03-15 28 views
1

對於下面的代碼,我使用隱藏的,當我在這兩條路由之間路由時,它調用ngOnInit()。但是,當我使用「* ngif」時,ngOnInit()從未被調用過。我想知道爲什麼發生。另外,如果可能的話,我想「* ngif」,因爲「[hidden]」可能與CSS發生衝突。爲什麼「[hidden]」有效,但「ngIf」在Angular2中對ngOnInit()不起作用?

<div class="container"> 
       <div [hidden]="!(router.url == '/info/userinfo')"> 
        <div class="catalog" > 
        <button [routerLink]="['/info/userinfo']"><h2>userinfo</h2></button> 
       </div> 
       <div [hidden]="!(router.url == '/info/question')"> 
        <div class="catalog"> 
        <button [routerLink]="['/info/question']"><h2>question</h2></button> 
        </div> 
       </div> 
    </div> 

userinfo和問題是兩個組件和信息的孩子。 我想它與路線有關,因爲如果我從'/ home'到'/ info/question',ngOnInit()將被調用。但是,如果我從'/ info/userinfo'轉到'/ info/question',則不會調用ngOnInit()。

+0

這在[Angular的文檔](http://angular.io)中討論。我強烈建議你看看,因爲它寫得很好 – Gab

回答

2

因爲* ngIf當評估爲false時不會創建您的組件,但隱藏只隱藏組件,但仍然創建它。

相關問題