angular 基本命令

ng new my-project  => 项目名

ng serve 开启服务,之后可以http://localhost:4200 访问

[attribute] 为属性绑定

(click) 为事件绑定

 

父子组件通信:

和vue一样,都是用发射机制

子组件中定义输入和输出

@Input attr

@Output nofity

@Output show

定义product-alert作为子组件:

product-alert.component.html:

<div *ngIf="product.price > 700">
  <button (click)="onNotifyByMe()">Notify by children</button>
  <div>
    <!-- 当这两个按键被点击触发,则往外部放射对应的事件 -->
    <button (click)="notify.emit()">Notify by children</button>
    <button (click)="show.emit()">Show by children</button>
  </div>
</div>

product-alert.component.ts:

import { Component, OnInit } from '@angular/core';
import { Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-product-alert',
  templateUrl: './product-alert.component.html',
  styleUrls: ['./product-alert.component.css']
})
export class ProductAlertComponent implements OnInit {

  // input 的输入绑定,外部传的是[]做属性绑定
  @Input() product;
  // output 往外放射,触发父组件的事件
  @Output() notify = new EventEmitter();
  @Output() show = new EventEmitter();

  constructor() { }

  ngOnInit() {
  }

  onNotifyByMe() {
    window.alert("notify by myself");
  }
}

可以看到在ts文件中定义了一个输入 product 和两个输出 notify和show

同时在html中通过两个按键绑定了这两个输出的触发事件,整个流程就好像子组件给父组件打了一个电话,告诉他父组件该干什么了,父组件接收到子组件的通知后,就开始做相对应绑定的事情

 

父组件中的定义:

product-list.component.html

<h2>Product</h2>

<!-- 动态显示List -->
<div *ngFor="let product of productList; index as productId">

  <!-- 可以同时绑定多个输出 -->
  <!-- [product] 绑定product到子组件中 -->
  <!-- () 接收子组件放射出来的事件 -->
  <app-product-alert [product]="product" (notify)="onNotify()" (show)="onShow()">
  </app-product-alert>

  <br/>
  <br/>
</div>

product-list.component.ts

import { products } from '../../../assets/products';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {

  productList = products;

  constructor() { }

  ngOnInit() {
  }


  onNotify() {
    window.alert("parent notify");
  }

  onShow() {
    window.alert("parent show");
  }

}

可以看到父组件中,用[product]向子组件中传递了product信息,同时用(notify)="onNotify()"和(show)="onShow()"来获取到子组件发射出来的事件,并绑定到自己的事件中去。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值