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}`; } }Two-way bindingBefore introducing two-way binding, let's first talk about a requirement: when the count value of the CounterComponent subcomponent changes, the value of initialCount in the AppComponent parent component needs to be updated synchronously. Through the above example, we know that we can listen to the change event of the CounterComponent subcomponent in the AppComponent parent component, and then update the value of initialCount in the change event. 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() 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>父组件当前值:{{ initialCount }}</p> <exe-counter [count]="initialCount" (change)="initialCount = $event"></exe-counter> ` }) export class AppComponent { initialCount: number = 5; }In fact, two-way binding is composed of two one-way binding: Model-> View data bindingView-> Model event bindingAngular [] implements model-to-view data binding, () implements View to model event binding. Combining the two of them [()] achieves two-way binding. Also known as banana in the box syntax. [()] Syntax examplecounter.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; // 输出属性名称变更: change -> countChange @Output() countChange: EventEmitter<number> = new EventEmitter<number>(); ... // 其余代码未改变 }app.component.ts
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; }As can be seen from the above, [( modelName)] can be split into two parts modelName and modelNameChange, [modelName] is used to bind input properties, (modelNameChange) is used to bind output properties. When Angular encounters binding syntax of the form [(modelName)] when parsing a template, it expects an input property named modelName and an output property named modelNameChange to be present in this directive. ngModel Readers who have used Angular 1.x should be familiar with the ng-model directive, which we use to achieve two-way binding of data. So is there a corresponding instruction in Angular? The answer is yes, it is the ngModel directive. ngModel two-way binding example
import { Component } from '@angular/core'; @Component({ selector: 'exe-app', template: ` <p>你输入的用户名是:{{ username }}</p> <input type="text" [(ngModel)]="username" /> ` }) export class AppComponent { username: string = ''; }ngModel form verification example
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 = ''; }The above example uses the exportAs attribute in the metadata information of the @Directive directive to obtain the ngModel instance and obtain the control Status, the control status is classified as follows: valid - the form value is valid pristine - the form value has not changed dirty - the form value has changed touched - The form has been accessed
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!

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment