Home Web Front-end JS Tutorial Introduction to Input and Output in Angular (with code)

Introduction to Input and Output in Angular (with code)

Mar 13, 2019 pm 01:51 PM
angular

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--;
    }
}
Copy after login

app.component.ts

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;exe-app&#39;,
  template: `
   <exe-counter [count]="initialCount"></exe-counter>
  `
})
export class AppComponent {
  initialCount: number = 5;
}
Copy after login

@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 &#39;@angular/core&#39;;
@Component({
    selector: &#39;exe-counter&#39;,
    template: `
      <p>当前值: {{ count }}</p>
      <button (click)="increment()"> + </button>
      <button (click)="decrement()"> - </button>
    `
})
export class CounterComponent {
    @Input(&#39;value&#39;) count: number = 0;
... // 其余代码未改变
}
Copy after login

app.component.ts

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;exe-app&#39;,
  template: `
   <exe-counter [value]="initialCount"></exe-counter>
  `
})
export class AppComponent {
  initialCount: number = 5;
}
Copy after login

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 &#39;@angular/core&#39;;
@Component({
    selector: &#39;exe-counter&#39;,
    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--;
    }
}
Copy after login

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 &#39;@angular/core&#39;;
@Component({
    selector: &#39;exe-counter&#39;,
    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[&#39;count&#39;]);
    }
    increment() {
        this.count++;
    }
    decrement() {
        this.count--;
    }
}
Copy after login

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);
Copy after login

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 &#39;@angular/core&#39;;
@Component({
    selector: &#39;exe-counter&#39;,
    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);
    }
}
Copy after login

app.component.ts

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;exe-app&#39;,
  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}`;
  }
}
Copy after login

@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 &#39;@angular/core&#39;;
@Component({
    selector: &#39;exe-counter&#39;,
    template: `
      <p>当前值: {{ count }}</p>
      <button (click)="increment()"> + </button>
      <button (click)="decrement()"> - </button>
    `
})
export class CounterComponent {
    @Input() count: number = 0;
    @Output(&#39;countChange&#39;) change: EventEmitter<number> = new EventEmitter<number>();
... // 其余代码未改变
}
Copy after login

app.component.ts


##

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;exe-app&#39;,
  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}`;
  }
}
Copy after login

Two-way binding

Before 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 &#39;@angular/core&#39;;
@Component({
    selector: &#39;exe-counter&#39;,
    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);
    }
}
Copy after login

app.component.ts

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;exe-app&#39;,
  template: `
   <p>父组件当前值:{{ initialCount }}</p> 
   <exe-counter [count]="initialCount" 
    (change)="initialCount = $event"></exe-counter>
  `
})
export class AppComponent {
  initialCount: number = 5;
}
Copy after login

In fact, two-way binding is composed of two one-way binding:

Model-> View data binding

View-> Model event binding

Angular [] 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 example

counter.component.ts

import { Component, Input, Output, EventEmitter } from &#39;@angular/core&#39;;
@Component({
    selector: &#39;exe-counter&#39;,
    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>();
    ... // 其余代码未改变
}
Copy after login

app.component.ts

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;exe-app&#39;,
  template: `
   <p>父组件当前值:{{ initialCount }}</p> 
   <exe-counter [(count)]="initialCount"></exe-counter>
  `
})
export class AppComponent {
  initialCount: number = 5;
}
Copy after login

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 &#39;@angular/core&#39;;
@Component({
  selector: &#39;exe-app&#39;,
  template: `
   <p>你输入的用户名是:{{ username }}</p> 
   <input type="text" [(ngModel)]="username" />
   `
})
export class AppComponent {
  username: string = &#39;&#39;;
}
Copy after login

ngModel form verification example

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;exe-app&#39;,
  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 = &#39;&#39;;
}
Copy after login
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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Let's talk about metadata and decorators in Angular Let's talk about metadata and decorators in Angular Feb 28, 2022 am 11:10 AM

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!

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

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!

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

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

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

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

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

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

Angular + NG-ZORRO quickly develop a backend system Angular + NG-ZORRO quickly develop a backend system Apr 21, 2022 am 10:45 AM

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!

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

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!

A brief analysis of independent components in Angular and see how to use them A brief analysis of independent components in Angular and see how to use them Jun 23, 2022 pm 03:49 PM

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!

See all articles