简体   繁体   English

Angular 模板不显示由另一个组件调用的方法生成的数据

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

I have two components ComponentA and ComponentB我有两个组件 ComponentA 和 ComponentB

COMPONENT A .ts CODE组件 A .ts 代码

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

COMPONENT A .html CODE组件 A .html 代码

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

When I click on the componentA template button I do see the console and the name in the browser.当我单击 componentA 模板按钮时,我确实在浏览器中看到了控制台和名称。

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

} }

COMPONENT B.html CODE组件 B.html 代码

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

But when I click on componentB button, I can see the console.log data, but the name does not appear on the browser.但是当我点击componentB按钮时,我可以看到console.log数据,但是浏览器上没有显示名称。 Can anyone tell me what I've not done谁能告诉我我没有做过什么

The reason is that you are not binding name in ComponentB .原因是您没有在ComponentB绑定name With the inheritance from ComponentA , you only get the functionality implemented in component's class, not the template.通过从ComponentA继承,您只能获得在组件类中实现的功能,而不是模板。

In your ComponentB template, you have to do the following:在您的ComponentB模板中,您必须执行以下操作:

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

Check this demo as an example, where I have inherited AppComponent in ChildComponent勾选此演示作为一个例子,在那里我继承AppComponentChildComponent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular2:从另一个组件调用时不会触发订阅的方法 - Angular2: Subscribed Method is not fired when called from another component 将 Angular Material Table 中的行数据显示到另一个组件中 - Displaying row data from Angular Material Table into another component 角度单元测试是否根据服务中的数据调用了组件方法 - Angular unit test if component method is called according to a data from a service 角。 来自另一个组件更新模型的组件的调用方法,但不要更新被调用组件的视图 - Angular. Calling method of component from another component update model, but don't update the view of called component 从Angular 4中的另一个组件访问组件方法 - Access a component method from another component in Angular 4 来自 API 的数据未显示在 Angular html 模板中 - Data from API not displaying in Angular html template Angular - 来自数组的数据未显示在模板中 - Angular - Data from array not displaying in Template 模板中组件的Angular2调用方法 - Angular2 calling method of component from template Angular 5-数据未显示在模板中 - Angular 5 - Data not displaying in template 数据未显示在模板上(角度) - Data is not displaying on template (Angular)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM