網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
正文
在一些非常罕見(jiàn)的情況下,你可能需要直接從父組件中調(diào)用子組件的方法。一般來(lái)說(shuō),這應(yīng)該被看作是最后的手段。在大多數(shù)情況下,組件通信應(yīng)該限于數(shù)據(jù)綁定(包括輸入和輸出),以及在某些情況下,使用服務(wù)在兩個(gè)組件之間發(fā)送值。
然而,有些時(shí)候,我在兩個(gè)組件之間出現(xiàn)了競(jìng)賽條件,而這些條件只有通過(guò)非常精確的方法調(diào)用順序才能解決。這意味著,我需要它們同步發(fā)生。為此,這個(gè)方法是一個(gè)救命稻草,而且也很簡(jiǎn)單
考慮到我有以下組件
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss']
})
export class ParentComponent implements OnInit {
}
子組件:
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {
callMe(value : string) {
console.log('Called : ' + value);
}
}
在parent.component.html的視圖中,我放置了子組件:
<app-child></app-child>
現(xiàn)在在我的父組件中,我可以像這樣使用ViewChild來(lái)獲得對(duì)子組件的直接引用:
export class ParentComponent implements OnInit {
@ViewChild(ChildComponent, {static : true}) child : ChildComponent;
}
注意,我沒(méi)有像我們有時(shí)使用ViewChild那樣傳入一個(gè) "字符串 "來(lái)查找,我們傳入的是我們正在尋找的組件的實(shí)際類型。
組件調(diào)用
然后,這就像在我們的孩子身上調(diào)用一些東西一樣簡(jiǎn)單:
export class ParentComponent implements OnInit {
@ViewChild(ChildComponent, {static : true}) child : ChildComponent;
callMyChild(){
child.callMe('Calling from the parent!');
}
}
然而,通常的ViewChild規(guī)則適用,一般來(lái)說(shuō),你只能在視圖初始化后訪問(wèn)ViewChild引用(所以你不能在ngOnInit方法中訪問(wèn)它們,你必須使用ngAfterViewInit)。
同樣,使用數(shù)據(jù)綁定或 "連接服務(wù) "來(lái)讓兩個(gè)組件進(jìn)行通信通常會(huì)好得多。但往往很難同步需要發(fā)生的動(dòng)作的精確順序。因此,對(duì)于這一點(diǎn),ViewChild是贏家。
原文鏈接:https://juejin.cn/post/7176280435138232381
相關(guān)推薦
- 2022-09-22 YOLO v5模型的yaml文件參數(shù)理解
- 2023-03-23 React?Render?Props共享代碼技術(shù)_React
- 2022-03-03 Failed to execute ‘drawImage‘ on ‘CanvasRenderingC
- 2022-03-03 實(shí)現(xiàn)不需要手動(dòng)浮空瀏覽器緩存,程序可以獲取最新版本
- 2023-01-03 C++定義和初始化string對(duì)象實(shí)例詳解_C 語(yǔ)言
- 2021-12-06 c#二叉樹(shù)存儲(chǔ)介紹_C#教程
- 2021-12-29 CentOS系統(tǒng)rpm安裝Nginx和配置_nginx
- 2023-11-22 fatal: unable to access ‘https://github.com/xxxxx/
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支