Angular 组件负载上的角度变化变量
我有这个ruote配置:Angular 组件负载上的角度变化变量,angular,Angular,我有这个ruote配置: const routes: Routes = [ { path: 'score', component: ScoreComponent } ]; 加载组件分数时,我想更改父组件中变量的值 变量title位于父组件模板中: <div class="wrapper"> <app-header></app-header> <app-menu [variablesForMenu]='variablesForMe
const routes: Routes = [
{ path: 'score', component: ScoreComponent }
];
加载组件分数时,我想更改父组件中变量的值
变量title位于父组件模板中:
<div class="wrapper">
<app-header></app-header>
<app-menu [variablesForMenu]='variablesForMenu'></app-menu>
<div class="content-wrapper">
<section class="content-header">
<h1>
{{title}}
</h1>
</section>
<section class="content">
<router-outlet></router-outlet>
</section>
</div>
</div>
{{title}}
我该怎么办
我想使用EventEmitter,但不知道如何使用三种方法:
next
em: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
Child.component.ts
variableToChange: any;
sub: Subscription;
constructor(someService: SomeService){}
ngOnInit() {
sub.add(this.someService.em.subscribe(value => this.variableToChange = whatever));
}
constructor(someService: SomeService){}
ngOnInit() {
this.someService.em.next(true);
}
variableToChange: any;
@Input() variable: any;
ngOnInit() {
this.variable = 'whatever';
}
@Output() em: EventEmitter<any> = new EventEmitter();
ngOnInit() {
this.em.emit('something');
}
variableToChange: any;
setVariable(event) {
this.variable = event; // event is emitted value
}
variableToChange: any;
sub: Subscription;
constructor(someService: SomeService){}
ngOnInit() {
sub.add(this.someService.em.subscribe(value => this.variableToChange = whatever));
}
constructor(someService: SomeService){}
ngOnInit() {
this.someService.em.next(true);
}
variableToChange: any;
@Input() variable: any;
ngOnInit() {
this.variable = 'whatever';
}
@Output() em: EventEmitter<any> = new EventEmitter();
ngOnInit() {
this.em.emit('something');
}
variableToChange: any;
setVariable(event) {
this.variable = event; // event is emitted value
}
Parent.component.html
<child [variable]="variableToChange"></child>
<child (em)="setVariable($event)"></child>
variableToChange: any;
sub: Subscription;
constructor(someService: SomeService){}
ngOnInit() {
sub.add(this.someService.em.subscribe(value => this.variableToChange = whatever));
}
constructor(someService: SomeService){}
ngOnInit() {
this.someService.em.next(true);
}
variableToChange: any;
@Input() variable: any;
ngOnInit() {
this.variable = 'whatever';
}
@Output() em: EventEmitter<any> = new EventEmitter();
ngOnInit() {
this.em.emit('something');
}
variableToChange: any;
setVariable(event) {
this.variable = event; // event is emitted value
}
您可以使用此代码检测组件何时加载。加载组件时触发此事件。您可以通过服务组件、父组件和分数组件获得标题。我添加了三种方法,其中一种是事件发射器。如何使用第三种方法?我在模板上没有子组件,它是由routerIf手动加载的如果您没有在父视图中导入子组件,那么事件发射器不是正确的解决方案。我认为“家长”是指将一个组件插入另一个组件。如果这些组件不相关,则需要使用BehaviorSubject。child.component.ts中的代码应该是:
ngOnInit(){this.someService.em.next(true);}