[英]how to communicate beetween 2 sibling component in angular 4?
i want to checkbox tick in one component and show data in different component when checkbox checked. 我想在一个组件中勾选复选框,并在选中复选框时在另一个组件中显示数据。
component 1 组成部分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>
component 2 want data if mapLegend.checked 如果mapLegend.checked,组件2需要数据
There are several ways to do it. 有几种方法可以做到这一点。 From your requirement, I consider that you want to
observe
the changes made in either of the components. 根据您的要求,我认为您希望
observe
两个组件中所做的更改。 So I'll suggest you to go for subject
. 所以我建议你去
subject
。
Create a subject
in a service. 在服务中创建
subject
。 Now, subscribe to the variable
in the components where you want to listen to any changes that has been. 现在,在要侦听所有更改的组件中订阅
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);
}
}
If you want to share the data, then create a variable in
SomeService
file and get its value whenever.next()
is fired.如果要共享数据,请在
SomeService
文件中创建一个变量,并在触发.next()
时获取其值。 You can actually share a common value from.next(your_value)
and then subscribing it in another component.实际上,您可以从
.next(your_value)
共享一个公共值,然后将其订阅到另一个组件中。
Here is the demo as you asked & Here is the code 这是您所要求的演示 & 这是代码
Tweak the above code to suit your requirement and increase efficiency. 调整上面的代码以适合您的需求并提高效率。 It has to be improved to match your specific needs
必须对其进行改进以满足您的特定需求
Still @Shashank Vivek is most generic way to do cross component communication. @Shashank Vivek仍然是进行跨组件通信的最通用方法。 If what you need is simply what you have discribe : if my checkbox is true, then initialize childComponent with my model as parameter, then you can do something like this :
如果您只需要描述一下:如果我的复选框为true,则使用我的模型作为参数初始化childComponent,则可以执行以下操作:
Component : 零件 :
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 : 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>
UPDATE 1 更新1
On Component.ts
in following code you can do any traitment you want : 在以下代码中的
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]);
}
}
or in component.html
: 或在
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>
You could use a shared service and send a notification from any component injecting the service. 您可以使用共享服务,并从任何注入该服务的组件发送通知。
Consider the following : 考虑以下 :
checkbox.service.ts 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);
}
}
And then in your components: 然后在您的组件中:
reciver.component.ts 接收器组件
To get the checkbox state you do: 要获取复选框状态,请执行以下操作:
constructor(private cs: CheckboxService) {
this.cs.checkboxObservable
.subscribe((checkboxState) => {
// getting the value
console.log(checkboxState);
});
}
sender.component.ts sender.component.ts
To set a new state for the checkbox you simply use: 要为复选框设置新状态,您只需使用:
changeCheckboxState(){
this.cs.changeCheckboxState(this.mapLegendCheckbox);
}
Note don't forget to add the service in the provides arrays and the component in the declarations array of the same module so you don't get any errors. 请注意 ,不要忘记将服务添加到providers数组中,并将组件添加到同一模块的clarifications数组中,这样就不会出现任何错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.