简体   繁体   English

角度6-使用组件属性作为相同的组件属性值

[英]Angular 6 - Use component props as same component attribute value

I have a component that is passing props down to a child component. 我有一个将道具传递给子组件的组件。 I would like to take the resulting value of [info] and use it as my condition for [value] 我想将[info]的结果值用作[value]条件

Basically, is the [info] prop equal to the String good-info ? 基本上, [info]道具等于String good-info吗? If yes, set value to Happy otherwise set it to Sad 如果是,请将值设置为“ Happy否则将其设置为“ Sad

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

Of course I could use the same calculation for value that I'm using for info but that seems redundant. 当然,我可以使用相同的计算value ,我使用的info ,但是这似乎是多余的。 Also the calculation used in the info prop is much longer than the example one shown above. 同样, info道具中使用的计算比上面显示的示例更长。

You can refer to the child component with a template reference variable (eg #child ), which will allow you to get the value of the info property. 您可以使用模板引用变量 (例如#child )来引用子组件,这将允许您获取info属性的值。 However, the code below causes an ExpressionChangedAfterItHasBeenCheckedError because one property depends on the other being set in the same detection cycle. 但是,下面的代码会导致ExpressionChangedAfterItHasBeenCheckedError因为一个属性取决于在同一检测周期中设置的另一个属性。

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

See this stackblitz for a demo. 有关演示,请参见此堆叠闪电战


The exception mentioned above can be avoided if you set value when a change event is triggered from the child component after info has been set: 如果在设置info后从子组件触发更改事件时设置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>

See this stackblitz for a demo. 有关演示,请参见此堆叠闪电战

I would suggest using a method doing your calculations (in this example only returning the nested attribute), something like 我建议使用一种方法进行计算(在此示例中仅返回嵌套属性),类似

class SomeComponent {
    calculate(row: any) {
        return row.calculation.anotherCalculation.information;
    }
}

Then, in your HTML you can do 然后,您可以在HTML中

<div *ngFor="let row of rows">
    <some-component [info]="calculate(row)"
                    [value]="calculate(row) === 'good-info' ? 'Happy' : 'Sad' "
    ></some-component>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM