Angular custom component attribute setting

Viewed 928

(anyone is welcome to rephrase my question, I am not sure how to word it)

Say I created an Angular component, something like this:

<app-my-test></app-my-test>

How can I allow the user to set options on and off by just typing the option into the component, something like this:

<app-my-test booleanCheck></app-my-test>

Then in my .ts file, I would like booleanCheck to be true if they added it, and false if they didn't add it. Below is a blitz to play around with. The goal is to get the console.log to log true if booleanCheck was added, and false if it was not added.

https://stackblitz.com/edit/angular-xr3p84?file=src%2Fapp%2Fapp.module.ts

I do NOT want this as an answer please:

<app-my-test booleanCheck="true"></app-my-test>
<app-my-test [booleanCheck]="true"></app-my-test>
4 Answers

You can leverage the setter of @Input which will be called if the input is available.

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

@Component({
  selector: 'my-test',
  templateUrl: './app.test.html',
  styleUrls: ['./app.test.css']
})
export class TestComponent implements OnInit {
  private _booleanCheck = false;

  @Input()
  set booleanCheck(param) {   // this is setter for booleanCheck input.
    this._booleanCheck = true;
  }

  ngOnInit() {
    console.log('ngOnInit');
    console.log(this._booleanCheck);
  }
}

Working copy is here - https://stackblitz.com/edit/angular-9ubmg7

You'll have to create a directive that will set the property for you in the host component (Note that the property may no longer be an @Input):

StackBlitz demo

@Component({
  selector: 'my-test',
  templateUrl: './app.test.html',
  styleUrls: [ './app.test.css' ]
})
export class TestComponent implements OnInit {
  public booleanCheck: boolean;

  ngOnInit() {
    console.log('ngOnInit');
    console.log(this.booleanCheck);
  }
}

@Directive({
   selector: '[booleanCheck]' 
})
export class BooleanCheck {
  constructor(@Host() @Self() @Optional() host: TestComponent) {
      host.booleanCheck = true;
  }
}

(For an even simpler solution, look here)

Since you are passing the attribute to the custom component, it is not possible to add it like how you want. You are passing the input to the custom component and it should be like

<app-my-test [booleanCheck]="true"></app-my-test>

In your component it can be taken like

@Input() booleanCheck;

And if its true / false, you can enable / disable the logs.

Hope I answered your question.

One solution might be to check if the variable booleanCheck is undefined or not. This will console.log(this.booleanCheck) an empty string:

<app-my-test booleanCheck></app-my-test>

This will console.log(this.booleanCheck) undefined

<app-my-test></app-my-test>

So you can maybe use that to assign false if undefined and true if it is an empty string

Related