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!