1.定义子组件
@Component({ selector: " app-product-detail " , templeteUrl: " ./product-detail/product-detail.html " , styleUrls: "" , }) export class ProductDetail{ }
添加装饰器说明是一个组件,selector指明了该组件使用的标签名,templeteUrl指定组件模板即html,styleUrls指定样式模板。
父组件使用该子组件
//父组件html <app-product-detail ></app-product-detail>
2.父组件向子组件传值
(1)子组件添加@Input,表示向子组件输入
export class ProductDetail{ @Input product; //定义input的属性 }
(2)父组件使用
<app-product-detail [product]= " product " ></app-product-detail> //product是父组件定义的属性
3.子组件向父组件推送事件
(1)子组件添加outPut,表示子组件向外推送事件
export class ProductDetail{ @Input product; @OutPut notify = new EventEmitter(); }
(2) product-detail.html内触发事件
<button (click)= " notify.emit() " >Notify Me</button> //子组件触发事件
(3) 父组件接收事件
<app-product-detail [product]= " product " (notify)= " 事件方法 " ></app-product-detail> //子组件向外推事件,父组件设置方法接受
可以通过事件触发向父组件传递值。
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did222768