angular 初探之父子组件之间传递数据

angular 初探之父子组件之间传递数据

当一个组件封装好后,却由于在组件里处理过多的数据,而这些数据每个使用这个组件的人都可能不同的时候,那么封装就是不合理的。

所以将更多的处理和数据的调用给与外部是很有必要的。

vue中通过属性和子组件事件的触发实现父子组件之间的通信,angular也是如此,只是写法略有不同。

  // 子组件中

  // son.ts
  @Input() data: info[] = [];
  @Output() tabSelected = new EventEmitter();
  handlerSelected() {
      this.tabSelected.emit(this.data[this.testIndex]);
  }
  
  son.html
  <li *ngFor="let item of data; let i = index">
  <a href="{{ item.link }}" (click)="handlerSelected(i)">
    {{ item.title }}
  </a>
  <span *ngIf="i === testIndex" class="active"></span>
</li>
// 父组件中
// father.ts

  menus: info[] = [
  { title: "衣物", link: "#" },
  { title: "鞋子", link: "#" },
  { title: "电脑", link: "#" },
  { title: "手机", link: "#" },
  { title: "电器", link: "#" },
  { title: "空调", link: "#" },
  { title: "水果", link: "#" },
  { title: "零食", link: "#" },
  { title: "农产品", link: "#" },
  { title: "汽车", link: "#" }
];
  handlerTest(v: info) {
  console.log(v)
}

// father.html

<app-root [data]= "menus" (tabSelected)="handlerTest($event)"></app-root>

对于父组件数据传输在子组件中使用@Input() data: info接收,父组件中的html上使用[data] = menus

子组件触发事件
```
// js
@Output() notify = new EventEmitter();

// 子组件中 html
<button (click)="notify.emit()">Notify Me

```

猜你喜欢

转载自www.cnblogs.com/daixixi/p/11504016.html
今日推荐