Thursday, October 11, 2018

Input property example in Angular 6

Input properties are inbound properties which flows into a component from a parent component. Input properties are setter properties marked with the @Input decorator.

In this example we shall see on how to declare a @Input property in a child component and how to pass value to it from the parent component. We will get the value of the @Input property and display it in the child components view template.

Let us start with the patent-child component example and extent it by adding a @Input property to it.

In the child component we declare the @Input property parentMessage

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  @Input() parentMessage: string
  constructor() { }
  ngOnInit() {
  }
}

In the child component’s template we will display the value of the @Input property parentMessage.

<p>
  Hello from child Component.<br/>
  @Input Message from Parent: <b>{{parentMessage}}</b>
</p>

Now we have to pass the value from the parent component, to do this we will first declare a property message in the parent component.

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

@Component({
  selector: 'app-route-app',
  templateUrl: './route-app.component.html',
  styleUrls: ['./route-app.component.css']
})
export class RouteAppComponent implements OnInit {
  message: string;
  constructor() { }

  ngOnInit() {
    this.message = 'Hello from Parent Component.'
  }
}

Then we can pass the property along with the selector tag of the child component as follows.

<table class="layoutTable">
  <tr>
    <td class="leftMenu">
        <a routerLink="/about" routerLinkActive="active">About</a><br/>
        <a routerLink="/contact" routerLinkActive="active">Contact</a><br/>
    </td>
    <td class="content">
      This is the Home page of the Routing Component
      <app-child [parentMessage] = 'message'></app-child>
      <router-outlet></router-outlet>
    </td>
  </tr>
</table>

In the output notice that the value passed from the parent component is displayed in the view template of the child component.




Search Flipkart Products:
Flipkart.com

No comments: