Angular - Using Local Variable
Parent components can get complete access to the child component throughlocal variable. However, parent component gets access to the child component in its template only.
Example - Usage of Local Variable to pass data
Let us create two component, ParentCounterComponent and ChildCounterComponent to understand the concept. The purpose of the ParentCounterComponent is to provide counter functionality through two button, increment and decrement button. The increment button will increment the counter and the decrement button will decrement the counter. Parent component will get the increment and decrement functionality from child component instead of implementing itself.
Step 1: Create child component, ChildCounter Component using angular CLI as shown below −
ng generate component ChildCounter CREATE src/app/child-counter/child-counter.spec.ts (597 bytes) CREATE src/app/child-counter/child-counter.ts (224 bytes) CREATE src/app/child-counter/child-counter.css (0 bytes) CREATE src/app/child-counter/child-counter.html (29 bytes)
Step 2: Declare a variable counter and two methods inc() and dec() to increment and decrement the counter respectively inside the child component −
child-counter.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-child-counter',
imports: [],
templateUrl: './child-counter.html',
styleUrl: './child-counter.css',
})
export class ChildCounter {
counter: number = 0
// increment and decrement counter
inc() { this.counter++ }
dec() { this.counter-- }
}
Step 3: Next, open parent component's template file, app.html and add child component along with an id, #child to access the child component.
<app-child-counter #child></app-child-counter>
Step 4: Next, add two buttons and bind click events with child component's inc() and dec() methods accessed through child identifier. Also, show the current value of counter using child identifier.
app.html
<p>counter: {{child.counter}}</p>
<button (click)="child.inc()">Increment</button>
<button (click)="child.dec()">Decrement</button>
<app-child-counter #child></app-child-counter>
<router-outlet />
Step 5: Next, include the given code inside app.ts file.
app.ts
import { Component, signal } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { ChildCounter } from './child-counter/child-counter';
@Component({
selector: 'app-root',
imports: [RouterOutlet, ChildCounter],
templateUrl: './app.html',
styleUrl: './app.css'
})
export class App {
protected readonly title = signal('expense-manager');
}
Output
Step 6: Finally, run the application and check whether the counter is working fine.