Home > Net >  Angular @Input adding a function possible?
Angular @Input adding a function possible?

Time:09-26

I am using Angular 12 and I have a child component and using the @Input decorator.

So I have something like this:

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

Here is the child component:

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 is currently boolean but I want a way to say: if (isRed === true) { redClass = '.red' }

How can I do that?

CodePudding user response:

The first issue is that func() is not a type, the correct syntax for the input would be:

@Input() myfunction: () => void = this.func;

Note that it might be a better design to expose a @Output and deal with the function outside of the component. Just a general thought as we don't have much info on your component.

CodePudding user response:

I'd recommend you look at the value in ngOnInit or ngOnChange (use the latter if the input may change during the component's lifetime).

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

or

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

Read about Angular lifecycle hooks here

CodePudding user response:

You could try to define the input field as a setter like so:

...

redClass = '';

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

...

And then in your parent component:

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