iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 12
1
Modern Web

Angular 8 從推坑到放棄系列 第 12

[Day11] Property 與 事件 Binding

Angular 中 Components 之間的傳遞資料的方式,就長得像下面這張圖。

Input() 裝飾器使用方式

@Input 的目的是確認資料綁定 input 特性 (properties)是可以在改變時被追蹤的。
基本上來說,它是 Angular 將 DOM 藉由特性綁定 (property bindings) 直接在組件注入數值的方法。

直接來看 Code 吧!

AppComponent 長這樣並且直接引用了 BankComponent

app.component.html

<app-bank-account bankName="RBC" account-id="4747"></app-bank-account>

bank-account.component.ts

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

@Component({
  selector: 'app-bank-account',
  templateUrl: './bank-account.component.html',
})
export class BankAccountComponent implements OnInit {
// This property is bound using its original name.
  @Input() bankName: string;
  // this property value is bound to a different property name
  // when this component is instantiated in a template.
  @Input('account-id') id: string;

  // this property is not bound, and is not automatically updated by Angular
  normalizedBankName: string;
  constructor() { }

  ngOnInit() {
  }

}

Outout() 裝飾器使用方式

@Output是用來觸發組件的客製化事件並提供一個通道讓組件之間彼此溝通。

使用Output裝飾器時通常搭配EventEmitter 一起使用.

EventEmitter

Angular 用來從元件的 @Output() 屬性中釋出一些值。EventEmitter 擴充套件了 Observable,並添加了一個 emit() 方法,這樣它就可以傳送任意值了。當你呼叫 emit() 時,就會把所傳送的值傳給訂閱上來的觀察者的 next() 方法。

還是看不懂的話,一樣直接來看Code吧

zippy.component.ts

export class ZippyComponent implements OnInit {
  visible: boolean = true;
  @Output() open: EventEmitter<any> = new EventEmitter();
  @Output() close: EventEmitter<any> = new EventEmitter();

  constructor() { }

  ngOnInit() {
  }

  toggle() {
    this.visible = !this.visible;
    if (this.visible) {
      this.open.emit(null);
    } else {
      this.close.emit(null);
    }
  }
}

zippy.component.html

<div class="zippy">
    <div (click)="toggle()">按我顯示</div>
    <div [hidden]="!visible">
      <ng-content></ng-content>
    </div>
 </div>

app.component.html

<app-zippy (open)="onOpen($event)" (close)="onClose($event)">
	<hello name="{{ name }}"></hello>
	<p>Start editing to see some magic happen :)</p>
</app-zippy>

顯示結果:

參考

  1. Angular 8 Complete Guide To Angular

  2. Input Angular.io

  3. [Day 19] Angular 2 Input(s) & Output(s) 傻傻分不清

  4. [筆記][Angular 2][Angular 4][Input][Output] 在 Angular 2/4 Component 之間的資料傳遞 Input / Output


上一篇
[Day 10] Angular Debug 技巧
下一篇
[Day12] 有關 Angular 畫面封裝
系列文
Angular 8 從推坑到放棄30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言