Angular @Input 可以添加一个函数吗?

Angular @Input adding a function possible?

我正在使用 Angular 12,我有一个子组件并使用 @Input 装饰器。

所以我有这样的东西:

 <hello
  isRed="true">
</hello>

这是子组件:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<h1 class="{{redClass}}">Test</h1>`,
  styles: [`h1 { font-family: Lato; } .red { background: red }`]
})
export class HelloComponent  {

  redClass;

  @Input() isRed: boolean = false;
}

isRed 目前是布尔值,但我想要一种表达方式:if (isRed === true) { redClass = '.red' }

我该怎么做?

您可以尝试将输入字段定义为 setter,如下所示:

...

redClass = '';

@Input() 
set isRed(arg: boolean) {
  if(arg) {
     this.redClass = 'red';
  }           
}

...

然后在你的父组件中:

<!-- the right isRed of the assignment is a property of the parent that holds true or false -->
<hello [isRed]="isRed"></hello>

我建议您查看 ngOnInit 或 ngOnChange 中的值(如果输入在组件的生命周期内可能发生变化,请使用后者)。

ngOnInit() {
    if(this.isRed){
        this.redClass = "red";
    }
}

ngOnChanges(changes: SimpleChanges) {
    if(changes.isRed.currentValue){
        this.redClass = "red";
    }
}

了解 Angular 生命周期挂钩 here

在模板中,只需执行

<h1 [class.red]="isRed">Test</h1>

这仅适用于 red css class 如果 isRed 是真实的。

如果父组件更新 isRed 的值,此方法也将更新 css。如果您想遵循命令式方法,请尝试更新 ngOnChanges 内的 redClass 变量而不是 ngOnInit.