本文摘自PHP中文网,作者青灯夜游,侵删。

相关教程推荐:angularjs(视频教程)
创建 Student class
就只有几个简单的属性(执行下面的属性可以快速生成)
ng generate class entity/student
1 2 3 4 5 | export class Student {
id: number;
name: string;
age: number;
}
|
创建child component
ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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
1 2 3 | <p *ngIf= "stu" >
{{stu.id}} -- {{stu.name}} -- {{stu.age}} <button (click)= "delete(stu.id)" > delete </button>
</p>
|
修改 app.component
ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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
1 2 3 4 5 6 | <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()的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
详解Angular中的observable(可观察对象)
浅谈Angular中http请求模块的用法
详解Angular中的ngmodule(模块)
了解一下Angular中的@input()和@output()
浅谈Angular项目中如何引入第三方ui库(Angular material)
详解Angular中为html元素添加css类的几种方式
浅谈Angular中优化绑定(脏检查)性能的小技巧
一文快速了解Angular中的ngrx/store框架
13个关于Angular的前端面试题(总结)
浅谈Angular中@viewchild的用法
更多相关阅读请进入《Angular》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » 了解一下angular中的@Input()和@Output()