我需要从另一个组件调用组件的ngOnInit
方法。我想要做的是,在另一个组件的点击事件上打开一个模态。
service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class CustomerCreateneweventService {
private subject = new Subject<any>();
sendMessage(message: boolean) {
console.log(message);
this.subject.next(message);
}
clearMessage() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
模态组件
import { Subscription } from 'rxjs/Subscription';
import { CustomerCreateneweventService } from '../../../services/customer/customer-createnewevent.service';
@Component({
selector: 'app-customer-home-createnewevent',
template: `
<app-modal [(visible)]="newEventWindowOpen">
<h3 style="text-align: center">Create a new project</h3>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" (click)="newEventWindowOpen != newEventWindowOpen">Close</button>
</div>
</app-modal>
`
})
export class CustomerHomeCreateneweventComponent implements OnInit {
newEventWindowOpen: boolean;
subscription: Subscription;
constructor(private createNewService:CreateNewProjectService,private messageService: CustomerCreateneweventService) {
this.subscription = this.messageService.getMessage().subscribe(
message => { this.newEventWindowOpen = message; });
}
}
我想从另一个组件切换此模态:
其他组件
import { Component, OnInit } from '@angular/core';
import { CustomerCreateneweventService } from '../../../services/customer/customer-createnewevent.service';
@Component({
selector: 'app-customer-home-leftsidebar',
template: '<h4 (click)="toggleModal()">Toggle</h4>',
styleUrls: ['./customer-home-leftsidebar.component.css']
})
export class CustomerHomeLeftsidebarComponent implements OnInit {
constructor(private messageService: CustomerCreateneweventService) {}
ngOnInit() {
}
toggleModal(){
this.messageService.sendMessage(true);
}
}
这两个组成部分没有亲子关系。我需要实现这种方法,因为还有许多其他组件应该能够切换这个模态。
答案 0 :(得分:0)
以上代码正常运作。我只需要添加组件到HTML代码
<app-customer-home-createnewevent></app-customer-home-createnewevent>