[英]How to change the parent reusable component's style from it's child component?
[英]How to change a parent component's varibale from a child component
我是 Angular 的新手。 我正在尝试从子组件访问/改变父组件的变量。 我画了一个小图来解释我的结构。
我检查了许多解决方案,例如:
但我无法解决我的问题。 我也创建了一个stackblitz 。 请看看我的代码。
时间选择器.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;
}
}
月份选择器.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
。
一位专家告诉我创建一个服务。 但是项目非常复杂,我无法对其进行更改。 这是一个团队项目。 是否有任何快速修复或不那么痛苦的解决方案。 请纠正我,因此我完全被阻止了。 这是堆栈闪电战。
看一下这个:
https://stackblitz.com/edit/angular-k6fnfk?file=src%2Fapp%2Fmonthpicker%2Fmonthpicker.component.html
您必须将x
传递给子组件,如下所示:
<app-monthpicker [x]="x" (outputToParent)="GetOutputVal($event)"></app-monthpicker>
然后在你的monthpicker(子)组件中:
@Input() x;
并更改x
值:
sendToParent() {
let newX = this.x + 1;
this.outputToParent.emit(newX);
}
单击按钮(或任何事件)时,您需要使用输出装饰器将值发送到父组件。
https://angular.io/guide/component-interaction#parent-listens-for-child-event
我编辑了您的 slackblitz,因为您没有在单击按钮时发出输出,现在它工作正常: https ://stackblitz.com/edit/angular-zhpbr8
我已经有了答案。 但我尝试了另一种方法。 我自己想到的。 如果它是错误的,请告诉我删除它。
逻辑:而不是直接点击父组件中的值或使用sendToparent
和this.outputToParent.emit(string);
. 我在父组件中创建了一个自定义的 mutator 函数,然后它会改变变量的状态。 我只是从子组件调用该方法。
我得到了以下帮助:
这是我的代码:
父组件.html
<app-child (parentFun)="parentFun()"></app-child>
父组件.ts
x : boolean=false;
...
parentFun(){
this.x=true;
}
子组件.html
<button (click)="buttonClicked()">Mutate</button>
子组件.ts
@Output("parentFun") parentFun: EventEmitter<any> = new EventEmitter();
....
buttonClicked() {
this.parentFun.emit();
}
这也对我有用。 通过这种方法,我还可以进行更多其他更改。 我所有的单元测试用例也在传递 Jasmine 和 Karma。
这是一个工作演示: Stackblitz
看看这个,Child to Parent:通过 Output() 和 EventEmitter 部分共享数据
使用@output 和EventEmitter 从子组件中的@angular/core 向父组件发出事件,我们可以通过从子组件触发事件来更改/修改父组件的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.