ng:input_output_for_child_and_parent_component_communication

Action disabled: revisions

@Input() @Output() for Child and Parent Component Communication

This example shows how @Input, @Output decorations work. To make is simple to read, this example is actually doing something not so particle in the real world…

In console, type:

>>ng g c parent
CREATE src/app/parent/parent.component.html (25 bytes)
CREATE src/app/parent/parent.component.spec.ts (628 bytes)
CREATE src/app/parent/parent.component.ts (269 bytes)
CREATE src/app/parent/parent.component.css (0 bytes)
UPDATE src/app/app.module.ts (680 bytes)

>>ng g c child
CREATE src/app/child/child.component.html (24 bytes)
CREATE src/app/child/child.component.spec.ts (621 bytes)
CREATE src/app/child/child.component.ts (265 bytes)
CREATE src/app/child/child.component.css (0 bytes)
UPDATE src/app/app.module.ts (758 bytes)

Here we create two variable that will be passed to the child component, and a function onChildButtonClicked() function that will be called when the child's button is clicked.

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

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
  iChildButtonClickedTime: number = 0;
  myString: string = "myString";
  myNumber: number = 1000;

  constructor() {
  }

  ngOnInit() {
  }

  onChildButtonCLicked($event: number) {
    this.iChildButtonClickedTime = $event
  }
}

The import part here is we bind myString, and myNumber to <app-child> component, and bind an emitter from the child to our onChildButtonClicked() function.

<p><app-child
    [inputString]="myString"
    [inputNumber]="myNumber"
    (toParentEmitter)="onChildButtonCLicked($event)"
  >
</app-child></p>
<p>Child component clicked times: {{iChildButtonClickedTime}}</p>

Here, we see the @Input and @Output decorations, which mapped in parent's html file. So, when this child component is created, the @Input values have already been set. Likewise, the output emitted is also be bind on create.

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


@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  iNumOfClick: number = 0;
  @Input() inputString: string;
  @Input() inputNumber: number;
  @Output() toParentEmitter = new EventEmitter<number>();

  constructor() {
  }

  ngOnInit() {
  }

  onButtonClicked() {
    this.iNumOfClick++;
    this.toParentEmitter.emit(this.iNumOfClick);
  }
}
<p> The number pass from parent is {{inputNumber}}</p>
<p> The string pass from parent is {{inputString}}</p>
<button (click)="onButtonClicked()">Click</button>
  • ng/input_output_for_child_and_parent_component_communication.txt
  • Last modified: 2019/11/22 12:01
  • by chongtin