相关教程推荐:angularjs(视频教程)
创建 Student class
就只有几个简单的属性(执行下面的属性可以快速生成)ng generate class entity/student
export class Student { id: number; name: string; age: number; }
创建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<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.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
<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对象给的参数,然后进行处理;
更多编程相关知识,可访问:编程教学!!