Angular元件間怎麼進行互動?常用互動方法介紹

2021-06-24 13:00:26
元件之間的互動主要是在主從元件之間進行互動。那麼元件之間怎麼進行互動?下面本篇文章給大家介紹一下Angular元件間進行常用互動的方法。

【相關教學推薦:《》】

1、通過輸入型繫結把資料從父元件傳到子元件

child.component.ts

export class ChildComponent implements OnInit {
  @Input() hero: any;
  @Input('master') masterName: string;      // 第二個 @Input 為子元件的屬性名 masterName 指定一個別名 master

  constructor() { }

  ngOnInit(): void {
  }

}

child.component.html

<div style="background-color: #749f84">
  <p>child works!</p>
  <h3>{{hero?.name}} says:</h3>
  <p>I, {{hero?.name}}, am at your service, {{masterName}}.</p>
</div>

parent.component.ts

export class ParentComponent implements OnInit {
  hero = {name: 'qxj'}
  master = 'Master'

  constructor() {
  }

  ngOnInit(): void {
  }

}

parent.component.html

<app-child [hero]="hero" [master]="master"></app-child>

2、父元件監聽子元件的事件

child.component.ts

export class ChildComponent implements OnInit {
  @Input()  name: string;
  @Output() voted = new EventEmitter<boolean>();
  didVote = false;

  vote(agreed: boolean) {
    this.voted.emit(agreed);
    this.didVote = true;
  }

  constructor() { }

  ngOnInit(): void {
  }

}

child.component.html

<h4>{{name}}</h4>
<button (click)="vote(true)"  [disabled]="didVote">Agree</button>
<button (click)="vote(false)" [disabled]="didVote">Disagree</button>

parent.component.ts

export class ParentComponent implements OnInit {
  agreed = 0
  disagreed = 0
  voters = ['Narco', 'Celeritas', 'Bombasto']

  onVoted(agreed: boolean) {
    agreed ? this.agreed++ : this.disagreed++
  }

  constructor() {
  }

  ngOnInit(): void {
  }

}

parent.component.html

<h2>Should mankind colonize the Universe?</h2>
<h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3>
<app-child *ngFor="let voter of voters" [name]="voter" (voted)="onVoted($event)"></app-child>

test1

3、父元件與子元件通過本地變數互動

父元件不能使用資料繫結來讀取子元件的屬性或呼叫子元件的方法。但可以在父元件模板裡,新建一個本地變數來代表子元件,然後利用這個變數來讀取子元件的屬性和呼叫子元件的方法,如下例所示。

子元件 CountdownTimerComponent 進行倒計時,歸零時發射一個導彈。startstop 方法負責控制時鐘並在模板裡顯示倒計時的狀態資訊。

child.component.ts

export class ChildComponent implements OnInit, OnDestroy {
  intervalId = 0
  message = ''
  seconds = 11

  clearTimer() {
    clearInterval(this.intervalId)
  }

  ngOnInit() {
    this.start()
  }

  ngOnDestroy() {
    this.clearTimer()
  }

  start() {
    this.countDown()
  }

  stop() {
    this.clearTimer()
    this.message = `Holding at T-${this.seconds} seconds`
  }

  private countDown() {
    this.clearTimer()
    this.intervalId = window.setInterval(() => {
      this.seconds -= 1
      if (this.seconds === 0) {
        this.message = 'Blast off!'
      } else {
        if (this.seconds < 0) {
          this.seconds = 10
        } // reset
        this.message = `T-${this.seconds} seconds and counting`
      }
    }, 1000)
  }

}

child.component.html

<p>{{message}}</p>

parent.component.ts

export class ParentComponent implements OnInit {
  constructor() {
  }
  ngOnInit(): void {
  }
}

parent.component.html

<h3>Countdown to Liftoff (via local variable)</h3>
<button (click)="child.start()">Start</button>
<button (click)="child.stop()">Stop</button>
<div class="seconds">{{child.seconds}}</div>
<app-child #child></app-child>

countdown timer

4、父元件呼叫@ViewChild()

這個本地變數方法是個簡單便利的方法。但是它也有侷限性,因為父元件-子元件的連線必須全部在父元件的模板中進行。父元件本身的程式碼對子元件沒有存取權。

如果父元件的需要讀取子元件的屬性值或呼叫子元件的方法,就不能使用本地變數方法。

當父元件需要這種存取時,可以把子元件作為 ViewChild,***注入***到父元件裡面。

countdown-parent.component.ts

import {AfterViewInit, Component, ViewChild} from '@angular/core'
import {ChildComponent} from '../child/child.component'

@Component({
  selector: 'app-parent-vc',
  template: `
    <h3>Countdown to Liftoff (via ViewChild)</h3>
    <button (click)="start()">Start</button>
    <button (click)="stop()">Stop</button>
    <div class="seconds">{{ seconds() }}</div>
    <app-child></app-child>
  `,
})
export class CountdownParentComponent implements AfterViewInit {

  @ViewChild(ChildComponent)
  private timerComponent: ChildComponent

  seconds() {
    return 0
  }

  ngAfterViewInit() {
    // Redefine `seconds()` to get from the `ChildComponent.seconds` ...
    // but wait a tick first to avoid one-time devMode
    // unidirectional-data-flow-violation error
    setTimeout(() => {
      this.seconds = () => this.timerComponent.seconds
    }, 0)
  }

  start() {
    this.timerComponent.start()
  }

  stop() {
    this.timerComponent.stop()
  }
}

更多程式設計相關知識,請存取:!!

以上就是Angular元件間怎麼進行互動?常用互動方法介紹的詳細內容,更多請關注TW511.COM其它相關文章!