输入属性@Input
装饰器 :当它通过属性绑定的形式被绑定时,值会“流入”这个属性 输出属性 @Output
装饰器:这个属性总是返回 EventEmitter 。 当它通过事件绑定的形式被绑定时,值会“流出”这个属性。 输入 属性 @Input 通常接收数据值。 输出 属性 @Output 暴露事件生产者,如 EventEmitter
对象。参考链接:https://www.cnblogs.com/yw0219/p/7768960.html
一. 父组件给子组件传值 @input()
父组件 father.component.ts 提供数据
import { Component} from "@angular/core" ;
@Component ( {
selector: "my-father" ,
templateUrl: "father.html"
} )
export class FatherComponent {
data: Array< Object> ;
constructor ( ) {
this . data = [
{ "id" : 1 , "name" : "html" } ,
{ "id" : 2 , "name" : "css" } ]
}
}
< my- child [ info] = "data" > < / my- child>
子组件 child.component.ts 获取数据
import { Component, Input} from "@angular/core" ;
@Component ( {
selector: "my-child" ,
templateUrl: "child.html"
} )
export class ChildComponent {
@Input ( )
info: Array< Object> ;
constructor ( ) {
}
}
< ul>
< li * ngFor= "let item of info" >
{ { item. name} }
< / li>
< / ul>
二. 子组件向父组件 emit 传值 @Output()
子组件 three-link.component.ts emit提供数据
import { Output, EventEmitter} from "@angular/core" ;
export class ThreeLinkComponent {
province: string;
@Output ( ) provinceOut = new EventEmitter ( ) ;
constructor ( ) {
this . province = "陕西" ;
}
}
provinceChange ( ) {
this . provinceOut. emit ( this . province) ;
}
父组件 接收数据
< three- link ( provinceOut) = "recPro($event)" > < / three- link>
recPro ( event) {
this . province = event;
}
三. 综合:通过 输入属性@Input() 以及 输出属性 @Output() 进行组件间传值
// 父组件 html
< li *ngFor = " let item of dataSet;let i = index" >
< span> {{item.name}}</ span> {{i+1}}--{{item.id}}
< app-child [names] = " item" (foo) = " bar($event)" > </ app-child> // 父组件传递属性【names】,接收事件(foo)
</ li>
dataSet = [
{ "id" : 0 , "name" : "张三" } ,
{ "id" : 1 , "name" : "李四" } ,
{ "id" : 2 , "name" : "王五" } ,
]
bar ( event: any) {
console. log ( event) ;
}
// 子组件 html
< input type = " button" value = " {{names.name}}" (click) = " todo($event)" />
export class ChildComponent implements OnInit {
@Input ( ) names: any = { }
@Output ( ) foo = new EventEmitter < string> ( )
this . foo. emit ( '你好' ) ;
}
constructor ( ) { }
ngOnInit ( ) {
}
}