gpt4 book ai didi

javascript - Angular 6 - 使用组件 Prop 作为相同的组件属性值

转载 作者:行者123 更新时间:2023-11-30 14:09:41 24 4
gpt4 key购买 nike

我有一个组件正在将 props 向下传递给子组件。我想获取 [info] 的结果值并将其用作 [value]

的条件

基本上,[info] 属性等于字符串 good-info 吗?如果是,将值设置为 Happy 否则将其设置为 Sad

<some-component [info]="row.calculation.anotherCalculation.information"
[value]="info === 'good-info' ? 'Happy' : 'Sad' "
></some-component >

当然,我可以对 value 使用与计算 info 相同的计算方法,但这似乎是多余的。 info 属性中使用的计算也比上面显示的示例长得多。

最佳答案

您可以使用 template reference variable 引用子组件(例如 #child),这将允许您获取 info 属性的值。但是,下面的代码会导致 ExpressionChangedAfterItHasBeenCheckedError,因为一个属性取决于在同一检测周期中设置的另一个属性。

<some-component #child 
[info]="row.calculation.anotherCalculation.information"
[value]="child.info === 'good-info' ? 'Happy' : 'Sad' ">
</some-component >

参见 this stackblitz用于演示。


在设置了info之后,如果在子组件触发change事件时设置value,就可以避免上面提到的异常:

export class SomeComponent {

private _info: string;

@Output() infoChanged = new EventEmitter<string>();

@Input() public get info(): string {
return this._info;
}
public set info(x: string) {
this._info = x;
this.infoChanged.emit(x);
}

@Input() public value: string;
}
<some-component #child 
[info]="row.calculation.anotherCalculation.information"
(infoChanged)="child.value = $event === 'good-info' ? 'Happy' : 'Sad'" >
</some-component>

参见 this stackblitz用于演示。

关于javascript - Angular 6 - 使用组件 Prop 作为相同的组件属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54711951/

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