angular4学习笔记整理(四)组件间通讯、管道

之后的笔记就写的快一点

组件间通讯

1.组件间通讯 。
父组件向子组件输入属性用
<app-order [stockCode]="stock" [amount]="100"></app-order>
子组件声明接收父组件的属性@input()注解

@Input()
amount: number;

2.组件输出属性

1.在发射的组件内部定义发射的EventEmitter对象

@Output()
lastPrice: EventEmitter<PriceQuote> = new EventEmitter();

2.在发射组件里 将要发射的变量发射出去 ,注意类型必须和定义里的泛型一致

let pq = new PriceQuote(this.stockCode, Math.random() * 100);
this.lastPrice.emit(pq);

3.在发射组件标签声明的地方加上监听该emitEvent对象传过来的事件

<app-price-quote (lastPrice)="priceQuoteHandler($event)"></app-price-quote>

然后父组件里就可以写,事件就是发射过来的值

priceQuoteHandler(priceQuote) {
  this.priceQuote = priceQuote;
}

注意想监听事件的名字即不是lastPrice 只要在output里改即可

@Output('priceChange')

但是这样有感觉很麻烦,能不能用双向绑定

还有注意 如果一个属性想用双向绑定 那么如果输入属性为rating ,并且想在标签上[(rating)],获取输出值那么在组件内的输出属性 名称必须为ratingChange ,加个Change

@Output()
private ratingChange: EventEmitter<number> = new EventEmitter();

管道

普通应用,这个使用可以去查官网

<p>{{birthday | date : 'yyyy-MM-dd HH:mm:ss'}}</p>
<p>{{pi | number: '2.2-4'}}</p>

自定义管道需命令行生成 ng g pipe name
管道和组件一样需申明在NgModule里

declarations: [
  FilterPipe
],

自定义管道

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
  transform(list: any[], filterField: string, keyword: string): any {
    if (!filterField || !keyword) {
      return list;
    }
    return list.filter( item => {
      let fieldVaule = item[filterField];
      return fieldVaule.indexOf(keyword) >= 0;
    });
  }
}

如何在父组件中调用子组件的方法

子组件就一个gretting的方法

父组件html代码
<app-children #child1></app-children>
<app-children #child2></app-children>
<button (click)="child2.gretting('jsex')">hahah1</button>

父组件ts代码

import { Component, OnInit, ViewChild} from '@angular/core';
import {ChildrenComponent} from './children/children.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit,{
  @ViewChild('child1')
  child1: ChildrenComponent;
  greeting: string = 'heelo';
  ngOnInit(): void {
    this.child1.gretting(this.greeting);
  }
}

1.在ts中调用子组件方法
html里

<app-children #child1></app-children>

ts里

@ViewChild('child1')
child1: ChildrenComponent;

父组件ts任意地方就可以

this.child1.gretting(this.greeting);

2.在html里调用子组件api

<app-children #child2></app-children>
<button (click)="child2.gretting('jsex')">hahah</button>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 一.课程简介 (注意:这里的AngularJS指的是2.0以下的版本) AngularJS的优点: 模板功能强大丰...
    壹点微尘阅读 4,498评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,153评论 19 139
  • 第一节:初识Angular-CLI第二节:登录组件的构建第三节:建立一个待办事项应用第四节:进化!模块化你的应用第...
    接灰的电子产品阅读 14,646评论 64 25
  • 组件基础 组件用来包装特定的功能,应用程序的有序运行依赖于组件之间的协同工作。组件是angular应用的最小逻辑单...
    oWSQo阅读 5,219评论 0 0
  • ​ 6月29日,上海上硕电气有限公司总经理张锋先生与中国•电圈子董事、电眼科技董事、温州城市合伙人、东正科技信息咨...
    电圈子阅读 2,622评论 0 0

友情链接更多精彩内容