【问题标题】:Toggle modal component from another sibling component从另一个同级组件切换模态组件
【发布时间】:2018-04-03 00:28:10
【问题描述】:

我需要从另一个组件调用一个组件的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);
  }    
}

这两个组件没有父子关系。我需要实现这种方法,因为还有许多其他组件应该能够切换相同的模式。

【问题讨论】:

  • 此外,您可能不应该手动调用生命周期方法;将模式重新打开到另一个公共方法中时,将重用的内容分解出来。
  • 没听懂
  • @AchiraShamal 他的意思是遵循这条规则:github.com/mgechev/codelyzer/issues/427
  • @JBNizet,我尝试实现你所说的,但是模态仍然没有切换。

标签: angular angular-components


【解决方案1】:

上面的代码正在运行。我只需要将组件添加到 html 代码中

<app-customer-home-createnewevent></app-customer-home-createnewevent>

【讨论】:

    猜你喜欢
    • 2016-10-14
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 2017-06-12
    • 2021-08-10
    • 1970-01-01
    • 2018-11-30
    • 2021-10-18
    相关资源
    最近更新 更多