Angular 5. Checking parents *ngIf in children component

I have two pages (diary.component and redactor.component) both draws the same component food.component, only with small difference: if it's diary.component - food should have an "add button". If it's redactor.component - food should have a delete button. I tried to solve this problem with boolean in parent components and check this state in food.component.html using *ngIf, but it doesn't work. Whats the problem, and how can I solve this? Here's my code for better understanding:

diary.component.ts

isDiary: boolean;
ngOnInit() {
    this.isDiary = true;
}

food.component.html

<div class="food">

  <button *ngIf="isDiary; else isRedactor" (click)="sendFood(food.name, food.nutritional_value)" class="add-btn" type="button">
    <i class="fas fa-plus"></i>
  </button>

  <ng-template #isRedactor>
    <button><i class="fas fa-times"></i></button>
  </ng-template>
  ...
</div>

Thank you !

Upvotes: 1

Views: 4150

Answers (2)

Alexandr2134
Alexandr2134

Reputation: 272

you have to create

@Input() isDiary: boolean;

inside of food.component.ts and pass the value from parent like so

<your-food-component [isDiary]="isDiary"></your-food-component>

Upvotes: 5

OClyde
OClyde

Reputation: 1076

So I'm assuming it's now always showing the add button?

This would be understandable, as you set your boolean to true in ngOnInit which will always happen when the component initializes!

Basically what you want is probably the definition of an @Input (https://angular.io/guide/component interaction) so you can conditionally pass it from the parent!

Using this way you can provide true in the parent where the add button should be shown and false in the parent where your else path should be taken!

Upvotes: 1

Related Questions