Home > Article > Web Front-end > Learn about @Input() and @Output() in angular
Related tutorial recommendations: angularjs(Video tutorial)
There are only a few simple attributes (execute the following attributes to quickly generate)ng generate class entity/student
export class Student { id: number; name: string; age: number; }
ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { Student } from '../entity/student'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { @Input() stu: Student; @Output() deleteEvent = new EventEmitter<number>(); constructor() { } ngOnInit() { } delete(id) { this.stu = null; this.deleteEvent.emit(id); } }
html
<p *ngIf="stu"> {{stu.id}} -- {{stu.name}} -- {{stu.age}} <button (click)="delete(stu.id)">delete</button> </p>
ts
import { Component } from '@angular/core'; import { Student } from './entity/student'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { stus: Student[] = [ {id: 1, name: '里斯', age: 3}, {id: 2, name: '里斯2', age: 4}, {id: 3, name: '里斯3', age: 5}, ]; stu: Student; constructor() { } selected(stu) { this.stu = stu; } deleteStu(id: number) { this.stus.forEach((val, index) => { if ( val.id === id) { this.stus.splice(index, 1); return; } }); } }
html
<p> <ul> <li *ngFor="let stu of stus" (click)="selected(stu)"> {{stu.id}} -- {{stu.name}} -- {{stu.age}} </li> </ul> </p> <app-child [stu]="stu" (deleteEvent)="deleteStu($event)"></app-child>
@Input()
It’s very simple, just give the data of the parent component to a property of the child component; @Output()
The child component creates an EventEmitter, The operation of the child component will trigger the EventEmitter, and then assign this EventEmitter object to a method of the parent component. The modified method will get the parameters given by the EventEmitter object and then process it;
For more programming-related knowledge, please visit : Programming Teaching! !
The above is the detailed content of Learn about @Input() and @Output() in angular. For more information, please follow other related articles on the PHP Chinese website!