gpt4 book ai didi

组件负载的 Angular 变化变量

转载 作者:太空狗 更新时间:2023-10-29 17:54:29 31 4
gpt4 key购买 nike

我有这样的配置:

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>

我该怎么办?

我想使用 EventEmitter 但我不知道如何使用

最佳答案

三种方法:

  1. 使用 BehaviorSubject,在父级订阅它并在初始化时在子级中调用 next

SomeService.service.ts

em: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

父组件.ts

variableToChange: any;
sub: Subscription;

constructor(someService: SomeService){}

ngOnInit() {
sub.add(this.someService.em.subscribe(value => this.variableToChange = whatever));
}

子组件.ts

constructor(someService: SomeService){}

ngOnInit() {
this.someService.em.next(true);
}

  1. 将变量作为输入从父级传递给子级,然后在子级初始化时更改该变量。

父组件.ts

variableToChange: any;

Parent.component.html

<child [variable]="variableToChange"></child>

子组件.ts

@Input() variable: any;

ngOnInit() {
this.variable = 'whatever';
}

  1. 使用事件发射器

子组件.ts

@Output() em: EventEmitter<any> = new EventEmitter();

ngOnInit() {
this.em.emit('something');
}

Parent.component.html

 <child (em)="setVariable($event)"></child>

父组件.ts

 variableToChange: any;

setVariable(event) {
this.variable = event; // event is emitted value
}

关于组件负载的 Angular 变化变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43939137/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com