欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Angular?ViewChild組件間通信demo

 更新時(shí)間:2022年12月13日 10:08:34   作者:Jovie  
這篇文章主要為大家介紹了Angular?ViewChild組件間通信demo,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

- ViewChild

這篇文章是Angular中組件間通信系列的一部分。雖然你可以從任何地方開(kāi)始,但最好還是從頭開(kāi)始,對(duì)嗎?

我們現(xiàn)在進(jìn)入了Angular中組件間交流的最后一個(gè)方法。這是一個(gè)我不確定是否真的應(yīng)該寫(xiě)出來(lái)的方法。你看,在我看來(lái),使用ViewChild來(lái)讓組件之間相互交流,是最后的手段。它不是那種反應(yīng)式的,而且經(jīng)常遇到各種競(jìng)賽條件,因?yàn)槟銢](méi)有使用像EventEmitters和數(shù)據(jù)綁定這樣的東西,而是直接調(diào)用方法。

由于上述原因,我打算把這段話說(shuō)得簡(jiǎn)短一些,因?yàn)樵诖蠖鄶?shù)情況下,你不會(huì)使用ViewChild在組件之間進(jìn)行通信,但知道它是一種選擇還是很好的。

通過(guò)ViewChild調(diào)用一個(gè)方法

想象一下,我有一個(gè)像這樣的AppComponent:

import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child/child.component';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild(ChildComponent, {static : false}) childComponent : ChildComponent;
  runChild() {
    this.childComponent.run();
  }
}

它也有像這樣的HTML:

<button (click)="runChild()">Click Me</button>
<app-child></app-child>

我們現(xiàn)在有一個(gè)AppComponent,有一個(gè)按鈕,當(dāng)點(diǎn)擊時(shí),將 "運(yùn)行 "我們的子組件。

還注意到我們使用了@ViewChild()指令來(lái)尋找HTML中的ChildComponent。有幾種不同的方法可以做到這一點(diǎn),例如,你可以在你的HTML中使用#name格式,然后用這個(gè)名字來(lái)尋找孩子,但重要的是,我們可以使用@ViewChild()來(lái)尋找html中的孩子元素,并獲得它們的引用。

我們的ChildComponent看起來(lái)像這樣:

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  run() {
    //Maybe a bunch of logic here. And then we set a message. 
    console.log("Run Successfully!" );
  }
}

沒(méi)有太多花哨的東西。在運(yùn)行這個(gè)解決方案時(shí),當(dāng)我們點(diǎn)擊AppComponent中的按鈕時(shí),它就會(huì)調(diào)用ChildComponent的運(yùn)行方法,一切都很好!這就是我們的解決方案。所以,首先要進(jìn)入的是。

以上就是Angular ViewChild組件間通信demo的詳細(xì)內(nèi)容,更多關(guān)于Angular ViewChild組件通信的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論