我發現了一些舊的答案,但它們使用的方法不再有效。我有一個頭組件嵌套組件中的角2調用方法
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { AuthenticationService } from '../_services/Authentication.Service';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
loading = false;
error = '';
isLoggedIn = false;
showMessageWindow = false;
messageType: string = "";
messageText: string = "";
public currentUser: any = null;
constructor(private _auth: AuthenticationService, private router: Router) { }
ngOnInit() {
if(this._auth.isLoggedIn()) {
this.isLoggedIn = true;
}
else {
this._auth.logout();
this.isLoggedIn = false;
this.router.navigate(['/']);
}
}
showMessage(message: string, type: string) {
this.messageText = message;
this.messageType = type;
this.showMessageWindow = true;
}
}
這是很基本的,表演和所管理內容的導航可以根據是否和誰登錄可以看到,我有一個內建在頭組件的警告/警報。並非所有頁面都使用標題,因此我將它導入使用它的組件,並將<app-header></app-header>
置於組件模板的頂部。
Here is a component that uses the header.
import { Component, OnInit } from '@angular/core';
import { HeaderComponent } from '../header/Header.Component';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-census',
templateUrl: './census.component.html',
styleUrls: ['./census.component.css']
})
export class CensusComponent implements OnInit {
constructor(private router: Router, private activatedRoute: ActivatedRoute) { }
ngOnInit() {
}
}
我希望能夠把一個方法到此組件,使得從頭部組件showMessage()
通話。我嘗試了幾種不同的方式,取得最小的成功。我最大的問題是如何引用嵌入式組件。我查看了文檔,但他們總是直接在組件中使用模板,並且不使用單獨的html文件。
如果我嘗試添加
@ViewChild(HeaderComponent)
private header: HeaderComponent;
到我CensusComponent我得到一個警告:
WARNING in ./src/app/header/Header.Component.ts
There are multiple modules with names that only differ in casing.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Use equal casing. Compare these module identifiers:
我已更新我的問題。我曾嘗試過這種方法,但是當我在上面的錯誤中添加該方法時。 – Jhorra
@Jhorra我更新了我的回答 –
投票贊成這個答覆,如果它解決了您的問題:p –