qingyun1029
qingyun1029

Reputation: 45

How two components communicate, in angular 2?

I wrote two components, as follows:

  1. DynSelectionComponent.ts (generic select tag, because the select tag does not support multi-select, filter, so this component uses ng2-selet).
  2. user-list.component.ts (this component corresponds to the html template using DynSelectionComponent, and provides a collection for DynSelectionComponent shown as option).

DynSelectionComponent.ts

import { Component, OnInit, ViewEncapsulation, Input, SimpleChanges } from '@angular/core';

@Component({
    selector: 'dyn-selection',
    template: `
    <ng-select [allowClear]="true"
                [items]="items"
                [disabled]="disabled"
                (data)="refreshValue($event)"
                (selected)="selected($event)"
                (removed)="removed($event)"
                (typed)="typed($event)"
                [placeholder]="placeholder">
    </ng-select>
    `,
})

export class DynSelectionComponent implements OnInit {
    @Input() inputItems: any[];//The other components are passed over the collection

    private value: any = {};
    private disabled: boolean = false;
    private placeholder: string = '';
    items: Array<any> = [];

    ngOnChanges(changes: SimpleChanges) {
        let newItems: any[] = [];
        for (let propName in changes) {
            if (propName == 'inputItems') {
                this.inputItems.forEach((compay: { companyId: string, companyName: string }) => {
                    newItems.push({
                        id: compay.companyId,
                        text: `${compay.companyName}`
                    });
                });
                this.items = newItems;
            }
        }
    }

    public selected(value: any): void {
        console.log('Selected value is: ', value);
    }
    public removed(value: any): void {
        console.log('Removed value is: ', value);
    }
    public typed(value: any): void {
        console.log('New search input: ', value);
    }
    public refreshValue(value: any): void {
        this.value = value;
    }
}

user-list.html(This file uses DynSelectionComponent)

<dyn-selection [inputItems]='companies' name="companyId" id="companyId"></dyn-selection>

user-list.component.ts(This component assigns a value for the companies property)

getCompanies(){        
    var url = "/api/company/queryCompany";
    this.httpPlus.post(url, {
        data:"c"
    }).subscribe((data: any) => {
        this.companies = data.data;
    }, (err)=> {
        this.companies = [];
    });
}

This time, user-list.html file can normally use DynSelectionComponent component, the normal display companies collection.

However, when triggers the onchange event, how does the user-list.component.ts component get the modified value of companyId ?

What should I do ? Thank you for your reply.

Upvotes: 0

Views: 331

Answers (2)

qingyun1029
qingyun1029

Reputation: 45

DynSelectionComponent.ts Add the following code

@Output("ValueOnChange")
ValueOnChange:EventEmitter<SelectItem> = new EventEmitter<SelectItem>();

When the ng2-select value changes:

public refreshValue(value: any): void {
    this.ValueOnChange.emit(value);
}

receiver: user-list.html(binding ValueOnChange event)

<dyn-selection [inputItems]='companies' (companyIdChange)="ValueOnChange($event)"></dyn-selection>

receiver: user-list.component.ts

ValueOnChange(company: SelectItem){
    console.log("The received value is: " + company.id);
}

Upvotes: 0

Praneeth Reddy
Praneeth Reddy

Reputation: 424

Components can communicate in two ways 1. parent and child relation. through @Input, @output and eventemitter 2. Through shared service.

https://angular.io/docs/ts/latest/cookbook/component-communication.html

If you have complex arch then you can use ngrx/store.

Upvotes: 1

Related Questions