簡體   English   中英

Angular 模板不顯示由另一個組件調用的方法生成的數據

[英]Angular template not displaying data generatd by a method called from another component

我有兩個組件 ComponentA 和 ComponentB

組件 A .ts 代碼

export class ComponentA implements OnInit {
 name: string;
 constructor() {}
 
 showName(){ 
    this.name = "Timothy";
    console.log('inside showName' + this.name);
 }
}

組件 A .html 代碼

 <button (click)="showName()">Click to see the name</button>    <div *ngIf="name?.length>0">{{name}}</div>

當我單擊 componentA 模板按鈕時,我確實在瀏覽器中看到了控制台和名稱。

export class ComponentB extends ComponentA  implements OnInit {
  constructor() { 
   super();
 }

}

組件 B.html 代碼

<button (click)="showName();">Show The Name</button>

但是當我點擊componentB按鈕時,我可以看到console.log數據,但是瀏覽器上沒有顯示名稱。 誰能告訴我我沒有做過什么

原因是您沒有在ComponentB綁定name 通過從ComponentA繼承,您只能獲得在組件類中實現的功能,而不是模板。

在您的ComponentB模板中,您必須執行以下操作:

<button (click)="showName();">Show The Name</button>
<div *ngIf="name?.length>0">{{name}}</div>

勾選此演示作為一個例子,在那里我繼承AppComponentChildComponent

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM