我是Angular的新手。我正在尝试从子组件访问/更改父组件的变量。我画了一个小图来解释我的结构。
我检查了许多解决方案,例如:
但是我无法解决我的问题。我还创建了一个stackblitz。请看一下我的代码。
timeselector.component.ts
import { Component, ViewChild } from '@angular/core';
import { MonthpickerComponent } from '../monthpicker/monthpicker.component';
@Component({
...
})
export class TimeselectorComponent {
x : boolean=false;
@ViewChild('primaryMonthPicker', {static: false}) primaryMonthPicker: MonthpickerComponent;
recievedFromChild:string="Intentionally left blank";
GetOutputVal($event) {
this.recievedFromChild=$event;
}
}
monthpicker.component.ts
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
...
})
export class MonthpickerComponent {
@Output() outputToParent = new EventEmitter<string>();
constructor() {}
sendToParent(string:string) {
this.outputToParent.emit(string);
}
buttonClicked() {
// some logic to access and change timeselector's x
console.log("Change handler called");
}
ngOnInit() {
}
}
我的实际问题比这复杂得多。但是我试图重现同样的东西。我只想了解完成工作的逻辑,然后我将按照自己的方式处理事情。我想将x
的值更改为true
。
一个专家告诉我要创建服务。但是该项目非常复杂,我无法对其进行更改。这是一个团队项目。是否有任何快速修复或较轻松的解决方案。请纠正我,因此我被完全阻止了。这是stackblitz。
答案 0 :(得分:2)
检查一下:
https://stackblitz.com/edit/angular-k6fnfk?file=src%2Fapp%2Fmonthpicker%2Fmonthpicker.component.html
您必须将x
传递给子组件,如下所示:
<app-monthpicker [x]="x" (outputToParent)="GetOutputVal($event)"></app-monthpicker>
然后在您的月份选择器(子)组件中:
@Input() x;
并更改x
的值:
sendToParent() {
let newX = this.x + 1;
this.outputToParent.emit(newX);
}
答案 1 :(得分:1)
单击按钮(或发生任何事件)时,您需要使用输出装饰器将值发送到父组件。
https://angular.io/guide/component-interaction#parent-listens-for-child-event
我编辑了您的slackblitz,因为您没有在单击按钮时发出输出,现在可以正常使用:https://stackblitz.com/edit/angular-zhpbr8
答案 2 :(得分:1)
我已经有了答案。但是我尝试了另一种方法。我一个人想到了。如果错误,请告诉我删除它。
逻辑:不要直接或使用sendToparent
和this.outputToParent.emit(string);
来击中父组件中的值。我在父组件本身中创建了一个自定义增变函数,该函数随后将更改变量的状态。我只是从子组件中调用该方法。
我从以下方面寻求帮助:
Angular : calling parent component function from child component
这是我的代码:
parent.component.html
<app-child (parentFun)="parentFun()"></app-child>
parent.component.ts
x : boolean=false;
...
parentFun(){
this.x=true;
}
child.component.html
<button (click)="buttonClicked()">Mutate</button>
child.component.ts
@Output("parentFun") parentFun: EventEmitter<any> = new EventEmitter();
....
buttonClicked() {
this.parentFun.emit();
}
这也为我工作。通过这种方法,我还可以做更多其他更改。我所有的单元测试用例也都传递给了Jasmine和Karma。
这是一个有效的演示:Stackblitz
答案 3 :(得分:0)
Share Data between components in Angular
签出,孩子对父母:通过Output()和EventEmitter部分共享数据
答案 4 :(得分:0)
使用@output和EventEmitter从子组件中的@ angular / core向父组件发出事件,我们可以通过触发子组件中的事件来更改/修改父组件值。