Javascript 为什么';发射';不要仅在我第一次单击按钮时显示名称?

Javascript 为什么';发射';不要仅在我第一次单击按钮时显示名称?,javascript,html,angular,typescript,Javascript,Html,Angular,Typescript,我想使用EventEmitter在单击按钮但不起作用时发送名称。第一次单击按钮时,不会显示名称,但如果再次单击,则会显示名称。 app.component.html app.component.ts 从'@angular/core'导入{Component}; 从“./name.service”导入{NameService}; @组成部分({ 选择器:“我的应用程序”, templateUrl:“./app.component.html”, }) 导出类AppComponent{ 名称:字

我想使用EventEmitter在单击按钮但不起作用时发送名称。第一次单击按钮时,不会显示名称,但如果再次单击,则会显示名称。

app.component.html


app.component.ts

从'@angular/core'导入{Component};
从“./name.service”导入{NameService};
@组成部分({
选择器:“我的应用程序”,
templateUrl:“./app.component.html”,
})
导出类AppComponent{
名称:字符串;
构造函数(私有名称服务:名称服务){
}
恩戈尼尼特(){
this.nameService.show.subscribe(name=>{
this.name=名称;
})
}
}
您好,component.ts

从'@angular/core'导入{Component,Input};
从“./name.service”导入{NameService};
@组成部分({
选择器:“你好”,
模板:`Hello{{name}}!`,
样式:[`h1{font-family:Lato;}`]
})
导出类HelloComponent{
名称:字符串;
构造函数(私有名称服务:名称服务){
}
恩戈尼尼特(){
this.nameService.show.subscribe(name=>{
this.name=名称;
})
}
}
name.service.ts

从'@angular/core'导入{EventEmitter};
导出类名称服务{
show=neweventemitter();
}
show.component.ts

从'@angular/core'导入{Component,Input};
从“./name.service”导入{NameService};
@组成部分({
选择器:“显示”,
模板:`单击以发射',
样式:[`h1{font-family:Lato;}`]
})
导出类ShowComponent{
名称:字符串;
构造函数(私有名称服务:名称服务){
}
show(){
this.nameService.show.emit('World');
}
}

EventEmitter
用于
@Output()
绑定,因为它具有异步发送值的选项。不要将其用于共享服务

<hello *ngIf="name"></hello>

这是因为您正在hello应用程序选择器上使用*ngIf。在app.component.ts中的name变量具有值之前,它不会初始化hello组件。因此,当您第一次单击emit时,name变量将首先被分配一个值,然后您的hello组件将被初始化。 然后,在您第二次单击hello应用程序中的名称变量后,将获得指定的值“world”,然后将显示该值

解决方案如下

<hello>
  <label *ngIf="name">
    {{name}}
  </label>
</hello>
<show></show>

{{name}}