angular组件使用

  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>  //子组件向外推事件,父组件设置方法接受
  
  可以通过事件触发向父组件传递值。
原文地址:https://www.cnblogs.com/hzozj/p/10996744.html