我需要做一些简单的事情,我想在单击帮助图标时显示一个对话框。
我有一个父组件:
@Component({
selector: 'app-quotation',
templateUrl: './quotation.component.html'
})
export class QuotationComponent implements OnInit {
public quotation: any = {};
public device: string;
public isDataAvailable = false;
@Output() showPopin: EventEmitter<string> = new EventEmitter<string>();
constructor(private quotationService: QuotationService,
private httpErrors: HttpErrorsService,
private popinService: PopinService) {}
moreInfo(content: string) {
console.log('here');
this.showPopin.emit('bla');
}
}
还有他的 html:
<ul>
<li *ngFor="let item of quotation.HH_Summary_TariffPageDisplay[0].content">
<label></label>
<i class="quotation-popin" (click)="moreInfo()"></i>
<div class="separator"></div>
</li>
</ul>
我的 popin 组件:
@Component({
selector: 'app-popin',
templateUrl: './popin.component.html',
styleUrls: ['./popin.component.scss']
})
export class PopinComponent implements OnInit {
public popinTitle: string;
public popinContent: string;
public hidden: boolean = true;
constructor() { }
openPopin(event):void {
console.log("here");
this.hidden = false;
}
}
他的 HTML:
<div class="card-block popin-container" (showPopin)="openPopin($event)" *ngIf="!hidden">
<div class="card">
<div class="popin-title">
{{ popinTitle }}
<i class="icon icon-azf-cancel"></i>
</div>
<div class="popin-content">
{{ popinContent }}
</div>
</div>
</div>
我的父组件加载到路由器导出中,我的 popin 加载到与路由器导出相同的级别,如下所示:
<app-nav-bar></app-nav-bar>
<app-breadcrumb></app-breadcrumb>
<div class="container">
<router-outlet></router-outlet>
</div>
<app-popin></app-popin>
我的问题是 eventEmitter 不起作用,我不知道为什么,有人可以解释一下吗?
谢谢,
问候
最佳答案
EventEmitters 仅适用于直接的父子组件关系。您与此处描述的组件没有这种关系。
在父子关系中,我们将在父级模板中看到子级的组件元素。我们在您的示例中没有看到这一点。
您有两个选择:
- 重构以使用父子关系
- 使用服务进行通信
如果您选择选项 2,服务应该只包含一个组件接下来调用的可观察对象,而另一个组件则订阅该可观察对象。
@Injectable()
export class PopinService {
showPopin = new ReplaySubject<string>(1);
}
将其注入(inject) QuotationComponent 并修改 moreInfo
moreInfo(content: string): void {
this.popinService.showPopin.next('bla' + content);
}
在 PopinComponent 中注入(inject) popinService 并添加以下内容:
ngOnInit() {
this.popinService.showPopin.subscribe(content => {
this.hidden = false;
this.popinContent = content;
});
}
关于javascript - Angular 2 eventEmitter 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44154957/