My menu is driven by MenuComponent and Login is driven by LoginComponent In my nav bar I have this :
<li *ngIf="!isConnected"><a [routerLink]="['/login']" class="btn btn-link">Login</a></li>
<li *ngIf="isConnected"><a href="" (click)="logout()">Logout</a></li>
How can I pass isConnected wich is a variable of MenuComponent, to True when I am in the méthode login() wich is in LoginComponent.ts ? Thank you for your help
答案 0 :(得分:0)
try using @Input and EventEmitters with @Output in the angular docs. component interaction angular.io
答案 1 :(得分:0)
我想我有一个解决方案(感谢Ploppy),它不是解决方案,但它简单而有效,这是我的代码:
服务:
import { Injectable } from '@angular/core';
@Injectable()
export class SharedService {
public isConnected: boolean;
constructor() { }
}
MenuComponent中
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {
@Input() isConnected: boolean;
constructor(private router: Router, private sharedService: SharedService){
this.sharedService.isConnected = false;
}
ngOnInit() {
}
logout() {
this.sharedService.isConnected = false;
this.router.navigate(['/home']);
}
}
LoginComponent
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
user: User;
isConnected: boolean = false;
constructor(private router: Router, private sharedService: SharedService) { }
ngOnInit() {
this.user = new User();
}
public login(){
if (...) {
this.partageService.isConnected=true;
this.router.navigate(['/home']);
}
}
}
AppComponent.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private router: Router, public sharedService: SharedService){}
}
AppComponent.HTML
<app-menu [isConnected]="sharedService.isConnected"></app-menu>
有点不便:它是带有logout()而不是LoginComponent的MenuComponent,它不是很正确,logout()不是MenuComponent的责任,而是LoginComponent! 解决这个问题的想法是什么?