Home>Article>Web Front-end> Learn about @Input() and @Output() in angular

Learn about @Input() and @Output() in angular

青灯夜游
青灯夜游 forward
2020-09-10 10:16:28 2845browse

Learn about @Input() and @Output() in angular

Related tutorial recommendations:angularjs(Video tutorial)

Create Student class

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; }

Create child component

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(); constructor() { } ngOnInit() { } delete(id) { this.stu = null; this.deleteEvent.emit(id); } }

html

{{stu.id}} -- {{stu.name}} -- {{stu.age}}

Modify app.component

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

  • {{stu.id}} -- {{stu.name}} -- {{stu.age}}

@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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete