Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular custom component attribute setting

Tags:

angular

(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>
like image 308
Freddy Bonda Avatar asked Nov 15 '18 06:11

Freddy Bonda


1 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

like image 161
Sunil Singh Avatar answered Sep 25 '22 17:09

Sunil Singh