Introduction to Input and Output in Angular (with code)
This article brings you an introduction to Input and Output in Angular (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Input is a property decorator, used to define input properties within the component. In practical applications, we mainly use it to transfer data from parent components to child components. Angular applications are composed of various components. When the application is started, Angular will start from the root component and parse the entire component tree, with data flowing from top to bottom to the next level of sub-components.
@Input()
counter.component.ts import { Component, Input } from '@angular/core'; @Component({ selector: 'exe-counter', template: ` <p>当前值: {{ count }}</p> <button (click)="increment()"> + </button> <button (click)="decrement()"> - </button> ` }) export class CounterComponent { @Input() count: number = 0; increment() { this.count++; } decrement() { this.count--; } }
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'exe-app', template: ` <exe-counter [count]="initialCount"></exe-counter> ` }) export class AppComponent { initialCount: number = 5; }
@Input('bindingPropertyName')
The Input decorator supports an optional Parameter used to specify the name of the component binding property. If not specified, the @Input decorator is used by default, and the decorated property name is used. Specific examples are as follows:
counter.component.ts
import { Component, Input } from '@angular/core'; @Component({ selector: 'exe-counter', template: ` <p>当前值: {{ count }}</p> <button (click)="increment()"> + </button> <button (click)="decrement()"> - </button> ` }) export class CounterComponent { @Input('value') count: number = 0; ... // 其余代码未改变 }
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'exe-app', template: ` <exe-counter [value]="initialCount"></exe-counter> ` }) export class AppComponent { initialCount: number = 5; }
setter & getter
setter and getter are used to constrain The setting and retrieval of attributes provide some encapsulation of attribute reading and writing, which can make the code more convenient and scalable. Through setters and getters, we encapsulate the private properties in the class to prevent external operations from affecting the private properties. In addition, we can also encapsulate some business logic through setters. The specific examples are as follows:
counter.component.ts
import { Component, Input } from '@angular/core'; @Component({ selector: 'exe-counter', template: ` <p>当前值: {{ count }} </p> <button (click)="increment()"> + </button> <button (click)="decrement()"> - </button> ` }) export class CounterComponent { _count: number = 0; // 默认私有属性以下划线开头,不是必须也可以使用$count biggerThanTen: boolean = false; @Input() set count (num: number) { this.biggerThanTen = num > 10; this._count = num; } get count(): number { return this._count; } increment() { this.count++; } decrement() { this.count--; } }
ngOnChanges
When the value of the data binding input attribute changes , Angular will actively call the ngOnChanges method. It will get a SimpleChanges object containing the new and old values of the bound properties. It is mainly used to monitor changes in component input properties. Specific examples are as follows:
import { Component, Input, SimpleChanges, OnChanges } from '@angular/core'; @Component({ selector: 'exe-counter', template: ` <p>当前值: {{ count }}</p> <button (click)="increment()"> + </button> <button (click)="decrement()"> - </button> ` }) export class CounterComponent implements OnChanges{ @Input() count: number = 0; ngOnChanges(changes: SimpleChanges) { console.dir(changes['count']); } increment() { this.count++; } decrement() { this.count--; } }
It should be noted in the above example that when the value of the input attribute is manually changed, the ngOnChanges hook will not be triggered.
Output is a property decorator used to define output properties within the component. Earlier we introduced the role of the Input decorator, and also learned that when the application starts, Angular will start from the root component and parse the entire component tree, with data flowing from top to bottom to the next level of sub-components. The Output decorator we introduced today is used to implement child components to notify information to parent components in the form of events.
Before introducing the Output property decorator, let us first introduce the hero behind EventEmitter. It is used to trigger custom events. The specific usage examples are as follows:
let numberEmitter: EventEmitter<number> = new EventEmitter<number>(); numberEmitter.subscribe((value: number) => console.log(value)); numberEmitter.emit(10);
The application scenario of EventEmitter in Angular is:
The sub-command creates an EventEmitter instance and exports it as an output attribute. The child instruction calls the emit(payload) method in the created EventEmitter instance to trigger an event. The parent instruction listens to the event through event binding (eventName) and obtains the payload object through the $event object. If it feels a bit abstract, let’s put it into practice right away.
@Output()
counter.component.ts import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'exe-counter', template: ` <p>当前值: {{ count }}</p> <button (click)="increment()"> + </button> <button (click)="decrement()"> - </button> ` }) export class CounterComponent { @Input() count: number = 0; @Output() change: EventEmitter<number> = new EventEmitter<number>(); increment() { this.count++; this.change.emit(this.count); } decrement() { this.count--; this.change.emit(this.count); } }
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'exe-app', template: ` <p>{{changeMsg}}</p> <exe-counter [count]="initialCount" (change)="countChange($event)"></exe-counter> ` }) export class AppComponent { initialCount: number = 5; changeMsg: string; countChange(event: number) { this.changeMsg = `子组件change事件已触发,当前值是: ${event}`; } }
@Output('bindingPropertyName')
The Output decorator supports an optional Parameter used to specify the name of the component binding property. If not specified, the @Output decorator is used by default, and the decorated property name is used. Specific examples are as follows:
counter.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'exe-counter', template: ` <p>当前值: {{ count }}</p> <button (click)="increment()"> + </button> <button (click)="decrement()"> - </button> ` }) export class CounterComponent { @Input() count: number = 0; @Output('countChange') change: EventEmitter<number> = new EventEmitter<number>(); ... // 其余代码未改变 }
app.component.ts
##
import { Component } from '@angular/core'; @Component({ selector: 'exe-app', template: ` <p>{{changeMsg}}</p> <exe-counter [count]="initialCount" (countChange)="countChange($event)"></exe-counter> ` }) export class AppComponent { initialCount: number = 5; changeMsg: string; countChange(event: number) { this.changeMsg = `子组件change事件已触发,当前值是: ${event}`; } }
import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'exe-counter', template: ` <p>子组件当前值: {{ count }}</p> <button (click)="increment()"> + </button> <button (click)="decrement()"> - </button> ` }) export class CounterComponent { @Input() count: number = 0; @Output() change: EventEmitter<number> = new EventEmitter<number>(); increment() { this.count++; this.change.emit(this.count); } decrement() { this.count--; this.change.emit(this.count); } }
import { Component } from '@angular/core'; @Component({ selector: 'exe-app', template: ` <p>父组件当前值:{{ initialCount }}</p> <exe-counter [count]="initialCount" (change)="initialCount = $event"></exe-counter> ` }) export class AppComponent { initialCount: number = 5; }
import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'exe-counter', template: ` <p>子组件当前值: {{ count }}</p> <button (click)="increment()"> + </button> <button (click)="decrement()"> - </button> ` }) export class CounterComponent { @Input() count: number = 0; // 输出属性名称变更: change -> countChange @Output() countChange: EventEmitter<number> = new EventEmitter<number>(); ... // 其余代码未改变 }
import { Component } from '@angular/core'; @Component({ selector: 'exe-app', template: ` <p>父组件当前值:{{ initialCount }}</p> <exe-counter [(count)]="initialCount"></exe-counter> ` }) export class AppComponent { initialCount: number = 5; }
import { Component } from '@angular/core'; @Component({ selector: 'exe-app', template: ` <p>你输入的用户名是:{{ username }}</p> <input type="text" [(ngModel)]="username" /> ` }) export class AppComponent { username: string = ''; }
import { Component } from '@angular/core'; @Component({ selector: 'exe-app', styles:[ `.error { border: 1px solid red;}` ], template: ` <p>你输入的用户名是:{{ username }}</p> <input type="text" [(ngModel)]="username" #nameModel="ngModel" [ngClass]="{error: nameModel.invalid}" required/> {{nameModel.errors | json}} ` }) export class AppComponent { username: string = ''; }
untouched - The form has not been accessed
The above is the detailed content of Introduction to Input and Output in Angular (with code). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This article continues the learning of Angular, takes you to understand the metadata and decorators in Angular, and briefly understands their usage. I hope it will be helpful to everyone!

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

Do you know Angular Universal? It can help the website provide better SEO support!

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

This article will share with you an Angular practical experience and learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!
