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

Angular?ViewChild組件間通信demo

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

- ViewChild

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

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

由于上述原因,我打算把這段話說得簡短一些,因為在大多數(shù)情況下,你不會使用ViewChild在組件之間進行通信,但知道它是一種選擇還是很好的。

通過ViewChild調(diào)用一個方法

想象一下,我有一個像這樣的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)在有一個AppComponent,有一個按鈕,當點擊時,將 "運行 "我們的子組件。

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

我們的ChildComponent看起來像這樣:

@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!" );
  }
}

沒有太多花哨的東西。在運行這個解決方案時,當我們點擊AppComponent中的按鈕時,它就會調(diào)用ChildComponent的運行方法,一切都很好!這就是我們的解決方案。所以,首先要進入的是。

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

相關(guān)文章

最新評論