【发布时间】:2018-09-25 21:40:02
【问题描述】:
我的 Angular 应用程序中有两个组件,一个是导航栏组件,一个是显示组件。在导航栏组件中有一个搜索按钮,用于搜索输入的名称并在显示组件中显示详细信息。那么如何我可以在显示组件中检查是否在导航栏组件中单击了搜索按钮,然后从导航栏组件中的搜索栏中获取名称,然后在显示组件中显示详细信息。我的意思是我只想在搜索按钮时单击的详细信息显示在显示组件中。由于它们是两个不同的组件,我无法了解如何在显示组件中为搜索按钮添加和单击事件侦听器。如何做到这一点?
这里是导航栏组件:
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse " id="navbarTogglerDemo01">
<ul id="nav-mobile" class="nav navbar-nav mr-auto">
<li ><h5 class="myId"></h5></li>
</ul>
<ul class="nav navbar-nav ml-auto" >
<li class="nav-item" *ngIf="isLoggedIn">
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2 ticketHold" type="search" placeholder="Search for a ticket" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0 ticketGet" (click)="search()">Search</button>
</form>
</li>
</ul>
</div>
</nav>
navbar.component.ts
import { Component, OnInit ,OnDestroy ,forwardRef,
ChangeDetectorRef} from '@angular/core';
import {UserLogs} from '../../model/UserLog';
import { AuthService } from '../../services/auth.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Router } from '@angular/router';
import { ViewEncapsulation } from '@angular/core';
import { ISubscription } from 'rxjs/Subscription';
@Component({
encapsulation: ViewEncapsulation.None,
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit , OnDestroy {
isLoggedIn:boolean;
isRegister:boolean;
private subscription: ISubscription;
constructor(private authService :AuthService,
private router : Router,
private flashMsg : FlashMessagesService,private changeDetectorRef:ChangeDetectorRef) { }
ngOnInit() {
this.subscription= this.authService.getAuth().subscribe(auth =>{
if(auth)
{
console.log('logged in '+localStorage.getItem("token"));
this.isLoggedIn=true;
// if(localStorage.getItem("token")=="user")
// {
// this.router.navigate(['/chat']);
// }
// else if(localStorage.getItem("token")=="consultant"){
// this.router.navigate(['/consultant']);
// }
}
else{
this.isLoggedIn=false;
console.log('Logged out hhdfd');
// this.router.navigate(['/']);
}
if (!this.changeDetectorRef['destroyed']) {
this.changeDetectorRef.detectChanges();
}
})
}
logOut()
{
localStorage.setItem("token","login");
this.authService.logout();
window.location.href="/";
if (!this.changeDetectorRef['destroyed']) {
this.changeDetectorRef.detectChanges();
}
}
search()
{
}
ngOnDestroy() {
this.changeDetectorRef.detach();
this.subscription.unsubscribe();
}
}
日
【问题讨论】:
-
可以使用组件交互angular.io/guide/…
-
你可以改变显示组件的输入,使用ngOnChange作为显示组件。粘贴你的代码我会修改它
-
您可以使用服务在显示组件中获取和显示数据。单击导航栏中的搜索按钮,您可以调用应该更新显示组件数据的服务方法。
标签: angular