Angular pass data from child to parent

I am studying / working on an Angular project, I have done a lot, and I try to do everything right, so now I want to do the following:

I want to get a variable (output) from a child component to a parent component, but I do not want to use the output, I do not want to listen to it, I want to get it whenever my parents need it, something like child.getVariable()I came across one message in which said that I should use childview, but the question was not like mine, so I want to know if it is good to use childview to get data from a child component or not?

+7
source share
4 answers

Register EventEmitter in your child component as @Output:

@Output() onDatePicked: EventEmitter<any> = new EventEmitter<any>();
Emit value on click:

public pickDate(date: any): void {
    this.onDatePicked.emit(date);
}

Listen for events in the template of the parent component:

<div>
    <calendar (onDatePicked)="doSomething($event)"></calendar>
</div>

and in the parent component:

public doSomething(date: any):void {
    console.log('Picked date: ', date);
}

Link: fooobar.com/questions/419390 / ...

+3
source

If you want to access a child component synchronously, it may be good practice to use ViewChild as follows:

import { CountryCodesComponent } from '../../components/country-codes/country-codes.component';
import { Component, ViewChild } from '@angular/core';

@Component({
    selector: 'signup',
    templateUrl: "signup.html"
})
export class SignupPage {
    @ViewChild(CountryCodesComponent)
    countryCodes: CountryCodesComponent;
    nationalPhoneNumber = '';

    constructor() {}

    get phoneNumber(): string {
        return '+' + this.countryCodes.countryCode + this.nationalPhoneNumber;
    }
}
+1
source

? , :

<child-component #childComponentRef></child-component>

# childComponentRef.someVariable . , Angular . . . https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-and-children-communicate-via-a-service

0

, Angular.

(i) EventEmitter, , - . .

(ii) . , , .

(iii) . , - . .

(iv) .

:

Angular Official website-

0

Source: https://habr.com/ru/post/1664054/


All Articles