父到子组件之间的数据传递
父组件模板中引用子组件
// father template: ...//...`
其中”fatherItemName” 为父组件中的属性,[name] 为子组件的输入
在子组件中使用 @Input() name 来接受父组件传递的值
如果在接收值前需要进行一些处理,可以使用setter 拦截输入属性
_name: string = '';
@Input()
set nameStr(name: string){
_name = "father name:" + name;
}
这时的 _name 作为临时变量,作为set 和get的中转。
父组件中:
< child-item [namestr] = “fatherItemName” >
name -> namestr
使用getter 输出
get nameStr(){ return _name; }
插值时 {{ nameStr }}
子到父组件之间的数据传递
1. 事件传值
// father template: ...//... export class FatherComponent{ fatherFunction(){ alert('hello!'); } }
子组件
//... < p (click) = "clickThis"> click p> //... @Output() childEvent = new EventEmitter(); clickThis(){ this.childEvent.emit(); }
2.父组件通过局部变量获取子组件的引用
子组件通过#绑定一个name的局部变量来访问子组件的属性
3.使用@ViewChild 获取子组件的引用
@ViewChild(ChildComponent) child: ChildComponent;
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



