2

I have a checkbox and textbox on a web page. Checkbox and Textbox are two independent components.

Textbox should be hidden till the moment checkbox is on. If checkbox is off - textbox should be hidden

Is it possible via directives ? Something like:

<checkbox></checkbox>
<textbox *ngIf="checkbox.value"></textbox>

Thank you in advance!

0

2 Answers 2

3

You just missed to identify the element that you are referring to and using its property.

one of the following two code should work for you:

<checkbox ngModel #myCheckbox></checkbox>
<textbox *ngIf="myCheckbox.value"></textbox>



<checkbox ngModel id="myCheckbox"></checkbox>
<textbox *ngIf="myCheckbox.value"></textbox>

This link can be useful for you : element-refs-in-angular-templates

Sign up to request clarification or add additional context in comments.

Comments

3

You can use EventEmitter and Input, Output in angular for components relations.

like this:

checkbox-component.html

<checkbox (change)="changeEvent()"></checkbox>

checkbox-component.ts

@Output checkboxChange: Eventemitter<boolean> = new Eventemitter<boolean>();

changeEvent(){
   // if checbox checked value is true else false
   this.checkboxChange.emit(value);
}

parent-component.html

<textbox-component [ShowValue]="checkBoxValue"></textbox-component>
<checkbox-component (checkboxChange)="onCheckboxChange($event)"></checkbox-component>

parent-component.ts

onCheckboxChange(value){
 this.checkBoxValue = value;
}

textbox-component.ts

  @Input() public set ShowValue(value: boolean) 
  {
    this.show = value;
  }

textbox-component.html

<textbox *ngIf="show"></textbox>

the parent component is your web page that contains your independent components.

1 Comment

Thank you, Hasan, it works but it looks like Habib solution is more elegant

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.