![](/img/trans.png)
[英]Cannot read property 'nativeElement' of undefined in angular when using @viewchild
[英]Cannot read property of undefined @ViewChild not working Angular 5
我遇到了一些麻煩,我似乎無法弄清楚為什么我的@ViewChild
工作..
基本上我想從另一個組件調用一個組件中的函數,所以在我的sidebar
組件中我有一個名為sendData()
的函數,我希望能夠通過單擊header
組件中的按鈕來調用它,所以我所做的是..
側邊欄組件
import { Component, OnInit, Input, OnChanges, SimpleChanges, AfterViewInit } from '@angular/core';
import * as _ from 'lodash';
@Component({
selector: 'app-sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.scss']
})
export class SidebarComponent implements OnInit, OnChanges {
constructor(
private contenfulService: ContentfulService,
private userService: UserService
) { }
ngOnInit() {
}
sendData(){
...do something
}
}
頭文件.component.ts
import { Component, OnInit, Input, ViewChild, EventEmitter } from '@angular/core';
import { UserService } from '../../../user.service';
import { SidebarComponent } from '../sidebar/sidebar.component';
@Component({
selector: 'app-program-header',
templateUrl: './program-header.component.html',
styleUrls: ['./program-header.component.scss']
})
export class ProgramHeaderComponent implements OnInit {
@ViewChild(SidebarComponent) sidebar;
constructor() { }
ngOnInit() {
}
}
header.component.html
<div (click)="sidebar.sendData()"></div>
但它不起作用我在控制台中收到此錯誤...
錯誤類型錯誤:無法讀取未定義的屬性“sendData”
為了簡潔起見,我刪除了代碼,所以如果您需要更多信息,請告訴我
我不確定是什么問題?
編輯
或者,如果有人知道另一種從單獨組件調用函數的方法,請告訴我
任何幫助,將不勝感激!
謝謝!
如果標題和側邊欄組件是同級,則不能在它們之間直接傳遞數據。 從角度看“輸出”和“輸入”。 或者,您可以使用服務在組件之間傳遞數據。 查看服務和可觀察物。
<parent>
<app-program-header>
</app-program-header>
<app-sidebar>
</app-sidebar>
</parent>
預期將使用ViewChild
從與選擇器匹配的當前組件的視圖(模板)中獲取目標元素。
但是,根據上述的評論,似乎沒有app-sidebar
放置在你的header.component.html
,所以ViewChild
是不是能夠得到這會導致你的電流誤差的有效元素。
解決方案應至少放置一次app-sidebar
。
<app-sidebar></app-sidebar>
<div (click)="sidebar.sendData()"></div>
就像這次對話的補充一樣,我被幾次追捕,原因似乎是@ViewChild
引用了未導入的模塊中的組件,而這似乎是缺少功能的@ViewChild
。 “無法讀取未定義的屬性”可能會極具誤導性,並且可能與@ViewChild
根本無關; 請務必先檢查您的進口。
在我的例子中——是從"@shared"
導入導致了這個問題。 您必須注意,您使用@ViewChild
組件引用的組件不在具有相同簡寫路徑的同一模塊中。 如果是,則從中導入@ViewChild
組件
'共享/組件/邊欄/sidebar.component'
而不是來自'@shared'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.