Angular @Input() Decorator

Angular @Input() Decorator is used to data transfer from parent component to the child component.

Suppose, there are two components App component is a parent component and UserList is a child component.

Now, you have to pass value of userPermission variable from “App Component” to “User Component” component.

Suppose you have to defined userPermission as a Boolean variable which has value true in the app.component.ts file.

Step1:- define userPermission in the app.component.ts file


import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  userPermission:boolean=true;

}

Now add the child component selector like app-user into the parent component html file (app.component.html).


<h1>Employees Management Tools</h1>
<app-user [permission]="userPermission"></app-user>

Step2:- Now, add the @input Decorator in the child component “user” and defined the permission variable, which is used in app.component.ts file


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

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.scss']
})
export class UserComponent implements OnInit {
  
  @Input() permission:boolean;
  constructor() { }

  ngOnInit(): void {
  }

}

Now, Add the condition based on permission in the user.component.html file.


<div *ngIf="permission">
    User allows to show this page.
</div>

<div *ngIf="!permission">
    User does not allow to show this page.
</div>

Now, if user set userPermission variable value true then show output on the browser “User can see the details.”

if user set userPermission variable value false then show output on the browser ” You have not permission to see the records”