溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Angular組件間進(jìn)行交互的方法有哪些

發(fā)布時間:2021-06-24 13:37:59 來源:億速云 閱讀:147 作者:chen 欄目:web開發(fā)

本篇內(nèi)容介紹了“Angular組件間進(jìn)行交互的方法有哪些”的有關(guān)知識,在實(shí)際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

1、通過輸入型綁定把數(shù)據(jù)從父組件傳到子組件

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>
  <h4>{{hero?.name}} says:</h4>
  <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、父組件監(jiān)聽子組件的事件

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

<h5>{{name}}</h5>
<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

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

Angular組件間進(jìn)行交互的方法有哪些

3、父組件與子組件通過本地變量互動

父組件不能使用數(shù)據(jù)綁定來讀取子組件的屬性或調(diào)用子組件的方法。但可以在父組件模板里,新建一個本地變量來代表子組件,然后利用這個變量來讀取子組件的屬性和調(diào)用子組件的方法,如下例所示。

子組件 CountdownTimerComponent 進(jìn)行倒計(jì)時,歸零時發(fā)射一個導(dǎo)彈。startstop 方法負(fù)責(zé)控制時鐘并在模板里顯示倒計(jì)時的狀態(tài)信息。

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

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

Angular組件間進(jìn)行交互的方法有哪些

4、父組件調(diào)用@ViewChild()

這個本地變量方法是個簡單便利的方法。但是它也有局限性,因?yàn)楦附M件-子組件的連接必須全部在父組件的模板中進(jìn)行。父組件本身的代碼對子組件沒有訪問權(quán)。

如果父組件的需要讀取子組件的屬性值或調(diào)用子組件的方法,就不能使用本地變量方法。

當(dāng)父組件需要這種訪問時,可以把子組件作為 ViewChild,***注入***到父組件里面。

countdown-parent.component.ts

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

@Component({
  selector: 'app-parent-vc',
  template: `
    <h4>Countdown to Liftoff (via ViewChild)</h4>
    <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組件間進(jìn)行交互的方法有哪些”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI