Component interaction in Angularjs – Part I


In Reactjs we used props to pass values to pass data to components , mean time Angularjs has different method for sharing data among components.

Angular used TypeScript, so better to learn some basics, almost everything in TS is same as JS does, with some changes. It is a superset of JS.

In this post we will discuss parent to child interaction.

Angular component and any custom component can pass property to another component. It didn’t send data directly, instead the data is stored in the parent class.

In our example we had a list component which is used to display a set of watch brands. The data is stored in the root component class.

The Project Structure

Angular Project Structure
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'BrnadComponent';
  blockTitle = 'Brands';
  blockData = ['ROLEX', 'SEIKO', 'FOSSIL', 'HUWAEI'];
}
//Template
<div>
  <H2>Property Binding Example</H2>
  <app-list [title]="blockTitle" [list]="blockData" ></app-list>
 
</div>

Receiving the data

We can get the data from the parent component ( app.component) using input (@Input) decorator function.

  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {
    @Input() public title:any;
    @Input('list') public brands:any;
  
  constructor() { 
 
  }

  ngOnInit(): void {
  }

Note that The data shared by the parent component ( blockData) is accepted as brands not blockData. We used an alias instead the property, this will help us to solve conflict among property and shared properties.

You can use the function with or without aiias

Keep reading Angular posts

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.