Angular 11 组件类和模板的交互及通信

多看官网:https://angular.cn/start

目录结构:

在这里插入图片描述

打开 product-alerts.component.ts

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

@Component({
  // @Component表明下面的类是一个组件
  selector: 'app-product-alerts',
  templateUrl: './product-alerts.component.html',
  styleUrls: ['./product-alerts.component.css']
})
// 导出用于处理该功能组件
export class ProductAlertsComponent implements OnInit {
  constructor() { }

  ngOnInit() {
  }

}

从 @angular/core 导入 Input。

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

在 ProductAlertsComponent 类的定义中,定义一个带 @Input() 装饰器的 product 属性。@Input() 装饰器指出其属性值是从该组件的父组件商品列表组件中传入的。

export class ProductAlertsComponent implements OnInit {
  @Input() product;
  constructor() { }

  ngOnInit() {
  }

}

打开 product-alerts.component.html

把作为占位符的 p 替换为如果商品价格超过 700 美元就要显示出来的“通知我”按钮。

<p *ngIf="product.price > 700">
  <button>Notify Me</button>
</p>

打开 product-list.component.html

通过属性绑定把当前商品作为输入传给组件。

<button (click)="share()">
  Share
</button>

//通过绑定的属性把超过700美金的商品下提示Notify Me
<app-product-alerts
  [product]="product">
</app-product-alerts>

当用户点击 “Notify Me” 时,产品提醒组件发出一个事件,商品列表组件对这个事件进行响应;

打开 product-alerts.component.ts

从 @angular/core 中导入 Output 和 EventEmitter

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

组件类中

在组件类中,用 @Output() 装饰器和一个事件发射器 EventEmitter() 实例定义一个名为 notify 的属性。这可以让商品提醒组件在 notify 属性发生变化时发出事件。

export class ProductAlertsComponent {
  @Input() product;
  @Output() notify = new EventEmitter();
}

打开product-alerts.component.html

product-alerts.component.html中,用事件绑定更新“Notify Me”按钮,以调用 notify.emit() 方法。

<p *ngIf="product.price > 700">
  <button (click)="notify.emit()">Notify Me</button>
</p>

点击按钮父组件采取行动

定义当用户单击该按钮时应该发生的行为。回想一下,应该由父组件(商品列表组件)采取行动,而不是商品提醒组件。在 product-list.component.ts 文件中,定义一个 onNotify() 方法,类似于 share() 方法:

export class ProductListComponent {
  products = products;

  share() {
    window.alert('The product has been shared!');
  }

  onNotify() {
    window.alert('You will be notified when the product goes on sale');
  }
}

在product-list.component.html

在 product-list.component.html 中,把 app-product-alerts 组件(就是它显示的“Notify Me”按钮)的 notify 事件绑定到商品列表组件的 onNotify() 方法。

<button (click)="share()">
  Share
</button>
//通过绑定的属性把超过700美金的商品下提示Notify Me
<app-product-alerts
  [product]="product" 
  (notify)="onNotify()">
</app-product-alerts>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值