如何在角4中的2兄弟组件之间进行通信?

时间:2018-04-16 11:25:49

标签: angular angular-forms

我想在一个组件中勾选复选框,并在选中复选框时在不同组件中显示数据。

组件1

<div class="col-md-6" *ngFor="let mapLegend of mapLegends">
            <label class="checkbox">
            <input type="checkbox"
            name="mapLegend"
            value="{{mapLegend.name}}"                            
            [(ngModel)]="mapLegend.checked"/>
            <span class="checkbox__input"></span>
            <span class="checkbox__label"> {{mapLegend.name}}</span>
            </label>
 </div>

组件2 想要数据,如果mapLegend.checked

3 个答案:

答案 0 :(得分:2)

有几种方法可以做到这一点。根据您的要求,我认为您希望observe在任一组件中进行的更改。所以我建议你去subject

在服务中创建subject。现在,订阅您希望收听任何更改的组件中的variable

export class SomeService{
    public mySubject = new Subject();
    choice: []<any>;

    insertCheckBoxValue(val){
        this.choice.push(val);
        this.mySubject.next('the value you want to transmit to all Subscribers'); // Let's say: Yoda
    }
}


export class Component1{
    constructor(private svc: SomeService){}

    this.svc.mySubject().subscribe( val => console.log(val)) // this will listen to the changes of Comp2 : Yoda

    checkBoxClicked(someVal){
        this.svc.insertCheckBoxValue(someVal);
    }

}

export class Component2{
    constructor(private svc: SomeService){}

    this.svc.mySubject().subscribe( val => console.log(val)) // this will listen to the changes of Comp1 : Yoda

    checkBoxClicked(someVal){
        this.svc.insertCheckBoxValue(someVal);
    }

}
  

如果要共享数据,请在SomeService文件中创建一个变量,并在.next()被触发时获取其值。实际上,您可以从.next(your_value)共享一个公共值,然后在另一个组件中订阅它。

Here is the demo as you asked&amp; Here is the code

调整上述代码以满足您的要求并提高效率。必须对其进行改进以满足您的特定需求

答案 1 :(得分:1)

仍然@Shashank Vivek是进行跨组件通信的最通用方式。如果您需要的只是您所描述的内容: 如果我的复选框为true,则使用我的模型作为参数初始化childComponent,然后你可以这样做:

组件:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  mapLegends: Array<{
    checked: boolean,
    name: string
  }>;

  constructor() {
    this.mapLegends = [
        {
          checked: false,
          name: 'Check 1'
        },
        {
          checked: false,
          name: 'Check 2'
        }
    ];
  }

  onCheckboxChange(index: number) {
    console.log(index);
    console.log(this.mapLegends[index]);
  }
}

html:

<div class="col-md-6" *ngFor="let mapLegend of mapLegends; let i = index">
    <label class="checkbox">
      <input type="checkbox"
      name="mapLegend"
      value="{{mapLegend.name}}"                            
      [(ngModel)]="mapLegend.checked" 
      (change)="onCheckboxChange(i)" />
      <span class="checkbox__input"></span>
      <span class="checkbox__label"> {{mapLegend.name}}</span>
    </label>
 </div>


 <div class="col-md-6" *ngFor="let mapLegend of mapLegends; let i = index">
   <hello *ngIf="mapLegend.checked" [name]="mapLegend.name"></hello>
 </div>

Online version

更新1

在以下代码中的Component.ts上,您可以执行任何所需的特征:

//This callback will be call on any change from checkbox. Up to you to do what ever you want.
  onCheckboxChange(index: number) {
    if(this.mapLegends[index]) {
      // Do what ever you want
      console.log(this.mapLegends[index]);
    }
  }

component.html

 <div class="col-md-6" *ngFor="let mapLegend of mapLegends; let i = index">
<!-- this section will be display only if checkbox is checked. -->
   <div *ngIf="mapLegend.checked">
      hello {{ mapLegend.name }} i am happy to see you.
   </div>
 </div>

答案 2 :(得分:1)

您可以使用共享服务并从注入服务的任何组件发送通知。

请考虑以下事项:

<强> checkbox.service.ts

import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';


@Injectable()
export class CheckboxService {
  // initial value false (not checked)
  public checkbox = new BehaviorSubject<boolean>(false);
  checkboxObservable = this.checkbox.asObservable();

  changeCheckboxState (value: boolean): void {
    this.checkbox.next(value);
  }
}

然后在你的组件中:

<强> reciver.component.ts

要获取复选框状态,请执行以下操作:

constructor(private cs: CheckboxService) {
    this.cs.checkboxObservable
       .subscribe((checkboxState) => {
              // getting the value
              console.log(checkboxState);
          });
    }

<强> sender.component.ts

要为复选框设置新状态,只需使用:

changeCheckboxState(){
this.cs.changeCheckboxState(this.mapLegendCheckbox);
}

注意 不要忘记在提供数组中添加服务,并在相同模块的声明数组中添加组件,这样就不会出现任何错误。