我正在尝试使用8号角@ViewChild来将变量从一个组件转换为另一个组件,但它会产生未定义的
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-signin',
templateUrl: './signin.component.html',
styleUrls: ['../styles/css/main.css']
})
export class SigninComponent implements OnInit {
isAuthenticated: any = false;
constructor() { }
ngOnInit() {
}
}
我想在signinComponent的navbar组件中使用isAuthenticated变量
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { SigninComponent } from "../signin/signin.component";
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['../styles/css/main.css']
})
export class NavbarComponent implements OnInit, AfterViewInit {
isAuthenticated: any;
@ViewChild(SigninComponent, {static: false}) signReference !: SigninComponent;
constructor() { }
ngOnInit() {
}
ngAfterViewInit() {
this.isAuthenticated = this.signReference.isAuthenticated
console.log(this.isAuthenticated)
}
}
这是navbar.component.html,其中包含isAuthenticated变量,用于验证导航栏的某些项目
<nav class="navbar navbar-expand-md navbar-dark bg-primary">
<div class="container">
<a href="#" class="navbar-brand">Mango App</a>
<button class="navbar-toggler" data-toggle="collapse" data-target="#navbarToggle">
<i class="navbar-toggler-icon"></i>
</button>
<div class="collapse navbar-collapse" id="navbarToggle">
<ul class="navbar-nav mr-auto" *ngIf="isAuthenticated">
<li class="nav-item">
<a href="" class="nav-link">Posts</a>
</li>
<li class="nav-item">
<a href="" class="nav-link">Messages</a>
</li>
</ul>
<ul class="navbar-nav ml-auto" *ngIf="!isAuthenticated">
<li class="nav-item">
<a routerLink="/signup" class="nav-link">SignUp</a>
</li>
<li class="nav-item">
<a routerLink="/signin" class="nav-link">Login</a>
</li>
</ul>
<ul class="navbar-nav ml-auto" *ngIf="isAuthenticated">
<li class="nav-item">
<a href="" class="nav-link">Change Password</a>
</li>
<li class="nav-item">
<a routerLink="/signup" class="nav-link">Logout</a>
</li>
</ul>
</div>
</div>
</nav>
如何处理角度8中的错误