Angular. Components interaction

Home » Tutorials » JavaScript » Angular. Components interaction
Today we’ll consider interaction between parent and child Angular components. Components with different levels of nesting can interact with middl service (we’ll talk about it in next videos).
We have to use @Input() and @Output() decorators for using interaction between parent and child Angular components. @Input() decorator describes input (from parent to child components) props. @Output property is EventEmitter, which “sends” child properties to the top level with using call emit() method.

We’ll also discuss the element links in Angular templates. To specify the link element, you need to add #elemLink for html tag (see code lesson)

Code lesson (app.component.html)

User info: {{user}}
<br><br>

Enter user name
<input type="text" #newUserName (input)="setNewUserName(newUserName.value)">

<br><br>

<hr>
<app-user [value]="user" (valueChanged)="user = $event"></app-user>

Code lesson (app.component.ts)

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  user = 'Kamil Abzalov';
  
  setNewUserName(newUserName: string) {
    this.user = newUserName;
  }
}

Code lesson (user.component.html)

User param in User component: {{value}}

<input type="text" #userName (input)="setNewUserName(userName.value)">

Code lesson (user.component.ts)

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

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent {

  @Input()
  value = '';

  @Output()
  valueChanged = new EventEmitter<string>();

  setNewUserName(newUserName: string) {
    this.valueChanged.emit(newUserName);
  }

}

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This