本文摘自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组件中的生命周期钩子
一文带你深入解析Angular 10
浅谈Angular8兼容ie10+版本的方法
浅谈Angular如何使用ng-content进行内容投影
深入了解Angular中的hostbinding和hostlistener装饰器
了解一下Angular中的@input()和@output()
聊一聊Angular中的路由(routing)
Angular和vue.js的区别是什么?Angular和vue.js的深度对比
深入了解Angular中的pipe(管道)
Angular的$watch方法详解
更多相关阅读请进入《Angular》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » 了解一下angular中的@Input()和@Output()