[英]Angular. Calling method of component from another component update model, but don't update the view of called component
使用ngx進行實驗時,注意到了這樣的功能:當嘗試從另一個組件調用組件的方法時,它會更新模型,但不會更新被調用組件的視圖。
接下來是情況:root.component的html中有test.component。 應該通過從任何其他組件調用該組件的方法來更改test.component的視圖。
app.component.html
<router-outlet></router-outlet>
<test-comp></test-comp>
Test.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'test-comp',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent {
public isVisible: boolean = false;
public setVisibility(isVisible: boolean) {
this.isVisible = isVisible;
}
}
Test.component.html
<div>
<p>Test component is visible: {{isVisible}}</p>
</div>
<div *ngIf="isVisible">
<p>Hi, this is test component!</p>
</div>
在其他一些組件中,調用test.component的相應方法:
export class LoginComponent implements OnInit {
constructor (private testComponent: TestComponent) {}
.....................................................
this.testComponent.setVisibility(true);
}
在調試器中,我可以看到模型已更改( this.isVisible = isVisible;
),但是模型未更新。
因此,我知道從另一個組件中調用組件的方法是一種非常糟糕的方法,但是我對細節感興趣:為什么這種情況下的視圖未更新?
有沒有辦法針對這種情況更新視圖?
感謝大伙們 !
嘗試使用ViewChild() ,在父組件中的構造函數之前聲明它:
@ViewChild(TestComponent) testComponent: TestComponent;
從父級到子級的調用:
this.testComponent.setVisibility(true);
希望這可以幫助 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.