angular4 method of parent component passing value to child component and child component passing value to parent component

Keywords: Javascript angular

Parent component passes value @ Input to child component

File directory

Parent component:

father.template.html

<h1>Parent component</h1>
<cmt-child [data]='data'></cmt-child>

father.component.ts

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

@Component({
    selector: 'cmt-father',
    templateUrl: './father.template.html'
})
export class FatherComponent implements OnInit {
    data: any = 'I am the value passed to the subcomponent'
    ngOnInit() {
    }

    ngOnChanges() {
    }

}

Sub component: (use @ Input modifier to receive)

childcomponent.ts

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

@Component({
    selector: 'cmt-child',
    templateUrl: './child.template.html'
})
export class ChildComponent implements OnInit {
    @Input() data: any;//Receive the value of the parent component
    ngOnInit() {
        console.log(this.data)
    }

    ngOnChanges() {
        console.log(this.data)
    }

}

This passes the value from the parent to the child!

Pass value from child component to parent component (pass value from child component to parent component through method with the help of modifier @ output)

Sub components

childcomponent.ts

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
    selector: 'cmt-child',
    templateUrl: './child.template.html'
})
export class ChildComponent implements OnInit {
    @Output('checked') checkedBack = new EventEmitter<any>();
    id:any ="I am the value passed to the parent component"
    ngOnInit() {
    }

    ngOnChanges() {
    }
    checkedCallback() {
        this.checkedBack.emit(this.id);
    }
}

child.template.html.html

<h1>Subcomponent</h1>
< button (click) ='checkedcallback() '> Click to transfer value to parent component < / button >

Parent component

father.template.html

<h1>Parent component</h1>
<cmt-child (checked)="checkedBack($event)"></cmt-child>

father.component.ts

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

@Component({
    selector: 'cmt-father',
    templateUrl: './father.template.html'
})
export class FatherComponent implements OnInit {
    ngOnInit() {
    }

    ngOnChanges() {
    }
    
    checkedBack(event) {
        console.log(event)
    }
}

In this way, the child component passes the value to the parent component by clicking!

Posted by j.smith1981 on Sat, 30 Nov 2019 13:42:26 -0800