網(wǎng)站首頁 編程語言 正文
正文
在一些非常罕見的情況下,你可能需要直接從父組件中調(diào)用子組件的方法。一般來說,這應(yīng)該被看作是最后的手段。在大多數(shù)情況下,組件通信應(yīng)該限于數(shù)據(jù)綁定(包括輸入和輸出),以及在某些情況下,使用服務(wù)在兩個(gè)組件之間發(fā)送值。
然而,有些時(shí)候,我在兩個(gè)組件之間出現(xiàn)了競(jìng)賽條件,而這些條件只有通過非常精確的方法調(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來獲得對(duì)子組件的直接引用:
export class ParentComponent implements OnInit {
@ViewChild(ChildComponent, {static : true}) child : ChildComponent;
}
注意,我沒有像我們有時(shí)使用ViewChild那樣傳入一個(gè) "字符串 "來查找,我們傳入的是我們正在尋找的組件的實(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ī)則適用,一般來說,你只能在視圖初始化后訪問ViewChild引用(所以你不能在ngOnInit方法中訪問它們,你必須使用ngAfterViewInit)。
同樣,使用數(shù)據(jù)綁定或 "連接服務(wù) "來讓兩個(gè)組件進(jìn)行通信通常會(huì)好得多。但往往很難同步需要發(fā)生的動(dòng)作的精確順序。因此,對(duì)于這一點(diǎn),ViewChild是贏家。
原文鏈接:https://juejin.cn/post/7176280435138232381
相關(guān)推薦
- 2022-09-17 Go語言學(xué)習(xí)筆記之錯(cuò)誤和異常詳解_Golang
- 2022-06-01 如何利用Python將字典轉(zhuǎn)為成員變量_python
- 2022-10-22 python常用數(shù)據(jù)結(jié)構(gòu)元組詳解_python
- 2022-11-27 Go?微服務(wù)開發(fā)框架DMicro設(shè)計(jì)思路詳解_Golang
- 2022-12-12 封裝flutter狀態(tài)管理工具示例詳解_Android
- 2024-03-14 Liunx安裝Redis
- 2023-01-13 Matlab中的mat數(shù)據(jù)轉(zhuǎn)成python中使用的npy數(shù)據(jù)遇到的坑及解決_python
- 2022-09-03 Pycharm中運(yùn)行程序在Python?console中執(zhí)行,不是直接Run問題_python
- 最近更新
-
- 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)證過濾器
- 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)程分支