A
A
Artem00712017-01-31 18:00:59
Angular
Artem0071, 2017-01-31 18:00:59

How to pass array to parent element?

Good afternoon!
Trying to learn Angular. Everything went well up to this point, namely the communication of the components among themselves.
Here I have 2 components:
app.component.ts

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

@Component({
    moduleId: module.id,
    selector: 'my-app',
    templateUrl: 'app.component.html'
})
export class AppComponent {

    myArr: any = [];

    myBTN(){
        console.log(this.myArr); // посмотреть что в массиве
    }

    onSetArr(newArr){
        this.myArr = newArr;
        console.log('123'); // чтобы видеть выполняется ли
    }
}

and child.component.ts
import { Component, OnInit, Output,EventEmitter} from '@angular/core';
import { Response} from '@angular/http';
import { HttpService} from '../../services/http.service';

@Component({
    moduleId: module.id,
    selector: 'child-app',
    templateUrl: 'child.component.html',
    providers: [HttpService]
})
export class AudiosComponent implements OnInit {
    myArr: any = [];
    constructor(private httpService: HttpService){}

    ngOnInit(){
        this.httpService.getData().subscribe((data: Response) => this. myArr =data.json());
    }

    @Output() onSetArr = new EventEmitter();

    setArr(newArr){
        this. onSetArr.emit(this. myArr);
    }
}

As a result, nothing works .. Well, that is, it works, there are no errors.
But nothing is passed to app.component ((
How can you pass an array from a child element to a parent element?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Shvedov, 2017-01-31
@mmmaaak

When you use a child component in a parent's template, do you bind the parent's onSetAttr handler to the child's onSetAttr event? There you also need to specify a parameter so that the data from the emit is forwarded

<child-app (onSetAttr)="onSetAttr($event)"></child-app>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question