相关教程推荐:angularjs(视频教程)
创建 student class就只有几个简单的属性(执行下面的属性可以快速生成)
ng generate class entity/student
export class student { id: number; name: string; age: number;}
创建child componentts
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>
修改 app.componentts
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() 很简单,就是将父组件的数据给子组件的一个属性;
@output() 子组件创建一个 eventemitter, 子组件的操作会触发eventemitter ,然后将这个 eventemitter 对象赋值给 父组件的一个 method ,改方法会拿到eventemitter对象给的参数,然后进行处理;
更多编程相关知识,可访问:编程教学!!
以上就是了解一下angular中的@input()和@output()的详细内容。