前言
小编最近在解决input与output的问题,做了一个小栗子给大家展示一下
input
表示的是父组件与子组件之间的属性的关系,input是由父组件流向子组件的过程。为什么会由父组件流向子组件呢?因为子组件需要获得父组件的值,所以必须是父组件给组件。在做input的时候我们必须有这几个步骤
- 父组件中的html标签是否用了子组件的选择器
- 父组件中的属性叫什么名字(记住,因为在子组件要用)
- 父组件中的模块用子组件的compont。
- 孩子组件component中用@input与你父组件的时候名称一样
- 孩子组件中html中进行显示
- 程序运行首先是走父组件,然后根据选择器和compont找到子组件和子组件的选择器
代码显示
dataparent.component.html
<app-datagridchild [values]="data"</app-datagridchild>
dataparent.component.ts
//声明数组
data: Array<Object>;
constructor() {
this.data = [
{
"id": 1,
"name": "王"
},
{
"id": 2,
"name": "雪"
},
{
"id": 3,
"name": "芬"
},
{
"id": 4,
"name": "ionic"
},
{
"id": 5,
"name": "node"
}
]
dataparent.module.ts
declarations: [
DataparentComponent,
DatagridchildComponent, //引入孩子的组件,然后找到组件进行显示
ChildComponent
]
孩子:datagridchild.component.ts
@Input()//属性
values:Array<object>;
datagridchild.component.html
<ul>
<li *ngFor="let item of values">
{{item.name}}
</li>
</ul>
页面显示效果
Output
Output是子组件向父组件流向,为什么这么说呢?因为output针对的是事件,如果我们我们触发事件肯定时从子组件触发,然后父组件去执行,执行的过程其实与input是一样的,就是在触发事件的时候有点不一样
- 父组件中的html标签是否用了子组件的选择器
- 父组件中的click事件叫什么名字(记住,因为在子组件要用)
- 父组件中的模块用子组件的compont。
- 父组件的compont中写一个点击事件的方法(执行相应的内容)
- 孩子组件component中用@Output与你父组件的时候名称一样
- 引用import { Component, OnInit, Input, , Output, EventEmitter, ,} from ‘@angular/core’;
- 孩子组件component中用 @Output() childEvent=new EventEmitter();
- 孩子组件component中执行相应的事件
- 孩子组件中html中进行显示
- 程序运行首先是走父组件,然后根据选择器和compont找到子组件和子组件的选择器
代码显示
dataparent.component.html
<app-datagridchild [values]="data" (childEvent) = "getChildEvent($event)"></app-datagridchild>
dataparent.component.ts
//点击事件,获取孩子传过来的index
getChildEvent(index){
console.log(index);
//表示删除从1到index元素
this.data.splice(index,1);
}
datagridchild.component.ts
@Output() childEvent=new EventEmitter<any>();
fireChildEvent(index){
//emit(按照参数的顺序执行每个监听器,如通有事件注册监听则返回true)
this.childEvent.emit(index);
}
datagridchild.component.html
<p *ngFor="let item of values; let i = index" (click)="fireChildEvent(i)">
{{item.name}}
</p>
由于是动态图,所以没有办法显示给大家看